Let me guess, a 32 bit build?
Consider these sizes:
At i 32 len: 3524578
At i 33 len: 5702887
At i 34 len: 9227465
At i 35 len: 14930352
At i 36 len: 24157817
At i 37 len: 39088169
At i 38 len: 63245986
At i 39 len: 102334155
At i 40 len: 165580141
At i 41 len: 267914296
At i 42 len: 433,494,437
This shows the length of ans at each i from 32 to 42 (in a 64 bit build).
I put commas in that last one so you can tell it's over 400 Mbytes. At 41, when the string was 267,914,296 bytes long, the space required to perform the concatenation and the set the result was at least the volume of the destination plus the two source strings.
Considering that you also grow first and second in this loop, I expect that you'll hit the limit of RAM in a 32 bit build.
You can get a little further with a 64 bit build, but this expansion is close to geometric. It explodes.
This isn't the limit of the string class, this is about the limit of RAM.
You may be able to squeeze a little more out of the available space by calling reserve in advance for the overall space ultimately required by your target (so the concatenations don't require string expansion within the loop), but that will buy you only as much as the limit of RAM in your machine (if you set for 64 bit build).
In Windows in a 32 bit build you're limited to 2Gbytes unless you set the OS and the application with the "big switch" to allow up to 3Gbytes. After that you must move to 64 bit.
On Linux that doesn't apply, but you are still limited to 4 GBytes (less some change) in 32 bit builds.