There are a few problems, all related to pointers and that leads to undefined behavior.
Lets start with this:
buffer[0]= (const char)"#vertices:\n #indices\n";
Here you take a pointer to a string literal, and tell the compiler to treat this pointer as a single character, and assign it to buffer[0]
, which at this point is a null pointer. Dereferencing a null pointer leads to undefined behavior, and is most likely the cause of the crash.
But it's not the only bad thing you're doing. Lets take this:
buffer=(unsigned char*)softWorld->getSoftBodyArray()[i];
Judging by your code softWorld->getSoftBodyArray()
probably returns either an std::array
or a std::vector
object. That means you take an element from this array or vector, and cast it to pointer and store it in buffer
. Again a case of undefined behavior because a single character (I assume) is not a pointer to something. You also do this in a loop, each iteration you loose the previous assignment. This won't cause a crash though, but then you do
fwrite(buffer, sizeof(unsigned char), softWorld->getSoftBodyArray().size(), file);
Here buffer
is not a valid pointer. Dereferencing this invalid pointer is again undefined behavior and could cause a crash.
There are also other things with your code that makes it suspect, like why are you using the old C file input/output functions instead of C++ streams?
You also open this file in binary mode, which indicates that you write binary data to the file, and yet you seem to be wanting to write some text also (I'm just guessing here, I don't know anything about the file format).
And finally, you want to write to the file, but you open it in read-only mode.