Why is this simple strcat crashing at runtime?

旧街凉风 提交于 2019-12-13 05:25:47

问题


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:


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.



来源:https://stackoverflow.com/questions/27872079/why-is-this-simple-strcat-crashing-at-runtime

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!