为什么这个简单的strcat在运行时崩溃? [英] Why is this simple strcat crashing at runtime?

查看:246
本文介绍了为什么这个简单的strcat在运行时崩溃?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

出于多年的不使用CI编程的经验回来之后,由于某种原因,它无法完成这项工作:

For some reason after coming back from years of not programming in C I cannot make this work:

(编译时没有任何抱怨,但在我崩溃时会导致崩溃删除可执行程序运行正常的strcat行)

(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;
}

此打印效果完美,但崩溃了我的exe。这是我的命令行(我使用的是Visual Studio 2010中的cl.exe):

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


推荐答案

您的代码崩溃了,因为您没有在 clibdir 中分配足够的空间来容纳初始字符串和附加字符串,因此您有缓冲区溢出。问题是,您已经浪费了 main()函数的返回堆栈,所以程序从返回时会陷入混乱,并崩溃()程序。您可能会发现,如果将 return 0; 替换为 exit(0); ,则您的程序不再崩溃。

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"!

合理的解决方法是将 clibdir 的大小从50增加到至少60。

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";

而不是:

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.

这篇关于为什么这个简单的strcat在运行时崩溃?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆