简体   繁体   中英

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:

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. 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.

Take a look at the malloc function, here's a link explaining it. https://www.tutorialspoint.com/c_standard_library/c_function_malloc.htm

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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