简体   繁体   English

C 中的 strcat() function 更改了我程序中的随机变量?

[英]The strcat() function in C changes a random variable in my program?

Here is the code I wrote:这是我写的代码:

int main(void){

  int m = 8;
  char digits[] = {};

  printf("%d\n" , m);
  strcat(digits, "0");
  printf("%d\n" , m);
}

I would expect the variable m to be unchanged but the output is this:我希望变量 m 保持不变,但 output 是这样的:

8
0

Why does this happen?为什么会这样? Any help would be very appreciated.任何帮助将不胜感激。

Your array 'digits' is not allocated any memory and has size of zero.您的数组“数字”未分配任何 memory 并且大小为零。 When you treat it execute 'strcat', C tries to do something using the address of your variable, overflows, and puts stuff into memory next to your variable's location.当你对待它执行'strcat'时,C 尝试使用你的变量的地址做一些事情,溢出,并将东西放入变量位置旁边的 memory 中。

Take a look at the malloc function, here's a link explaining it.看看 malloc function,这里有一个解释它的链接。 https://www.tutorialspoint.com/c_standard_library/c_function_malloc.htm https://www.tutorialspoint.com/c_standard_library/c_function_malloc.htm

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM