For some reason after coming back from years of not programming in C I cannot make this work:
(This compiles with no complain but it's causing a crash, when I remove the strcat line the executable runs fine)
#include <stdio.h>
#include <string.h>
int main(int argc, char **argv){
char clibdir[50] = "C:\\Users\\______000\\Desktop\\nodeC\\libraries\\c";
char varsfile[20] = "\\variables.xml";
printf("%s\n", clibdir); //ok
printf("%s\n", varsfile); //ok
char *varspath = strcat(clibdir, varsfile); //this is provoking a crash
printf("%s\n", clibdir); //prints right before crash
printf("%s\n", varspath); //prints right before crash
return 0;
}
This prints just perfectly but it's crashing my exe. This is my command line (I'm using cl.exe from Visual Studio 2010):
"%vcbin%\vcvars32.bat" && "%vcbin%\cl.exe" /nologo /EHsc main.cpp /link /subsystem:console
Your code is crashing because you've not allocated enough space in
clibdir
to hold the initial string and the appended string, so you have a buffer overflow. The trouble is, you've trashed the return stack from yourmain()
function, so the program goes haywire and crashes when you return from themain()
program. You'd probably find that if you replaced thereturn 0;
withexit(0);
, your program no longer crashes. That's coincidental — not a recommended fix.The moral of the story is "make sure there's enough space for the strings you append"!
The sane fix is to increase the size of
clibdir
from 50 to at least 60.…And…when you ask a question, make sure that the code you show in the question actually crashes the same as the code you are running on your machine. The original version of the question had:
instead of:
and no-one could understand why the code was crashing — because, indeed, the original code should not crash.