Why is this simple strcat crashing at runtime?

2019-09-03 15:05发布

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

1条回答
聊天终结者
2楼-- · 2019-09-03 15:48

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 your main() function, so the program goes haywire and crashes when you return from the main() program. You'd probably find that if you replaced the return 0; with exit(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:

char clibdir[50] = "\\libraries\\c";

instead of:

char clibdir[50] = "C:\\Users\\______000\\Desktop\\nodeC\\libraries\\c";

and no-one could understand why the code was crashing — because, indeed, the original code should not crash.

查看更多
登录 后发表回答