I have a main function which calls a function func, with a valid file path as a parameter. I use std::ifstream to open the file. Here's my code:
#include <stdlib.h>
#include <string>
#include <fstream>
int func(std::string filepath)
{
std::ifstream file(filepath);
file.close();
return 0;
}
int main()
{
std::string filepath = "file.txt";
func(filepath);
return 0;
}
On compiling the program with -O3 flag enabled and running it, I receive signal SIGSEGV, Segmentation fault. I use MinGW gcc version 9.2.0
g++ main.cpp -O3
./a
Here's the stack trace I get from gdb
(gdb) bt
#0 0x6fc03a47 in ?? () from C:\Program Files\Git\mingw32\bin\libstdc++-6.dll
#1 0x6fc1b4b2 in ?? () from C:\Program Files\Git\mingw32\bin\libstdc++-6.dll
#2 0x6fc1cb60 in ?? () from C:\Program Files\Git\mingw32\bin\libstdc++-6.dll
#3 0x004014c7 in basic_ifstream (__mode=std::_S_in, __s=..., this=0x22fdd4,
__in_chrg=<optimized out>, __vtt_parm=<optimized out>)
at c:/mingw/lib/gcc/mingw32/9.2.0/include/c++/istream:606
#4 _fu4___ZTVSt14basic_ifstreamIcSt11char_traitsIcEE () at main.cpp:7
#5 0x00404317 in main ()
at c:/mingw/lib/gcc/mingw32/9.2.0/include/c++/bits/char_traits.h:300
#6 0x00401233 in ?? ()
#7 0x004012e5 in mainCRTStartup ()
But it works fine if I compile it with -O3 flag disabled
It also works fine, If open the file from the main function itself
#include <stdlib.h>
#include <string>
#include <fstream>
int main()
{
std::string filepath = "file.txt";
std::ifstream file(filepath);
file.close();
return 0;
}
The above code works fine even with -O3 flag enabled
How can I make the first program work with -O3 flag enabled?