简体   繁体   中英

Char array in C overwritten with strncat()?

This is so weird. It seems that depending on which char array I declare/initialize first, a blank array is overwritten when I'm doing strncat() on the other array in C. code:

    char t_str[]="";
    char ran_str[]="";
    ... inbuf ="8889  ";
    while (inbuf[pos]!=' ')
    {
       strncat(t_str, &inbuf[pos],1);
       printf("t_str so far: %s\n", t_str);
       printf("ran_str so far: %s\n", ran_str);
       pos++;
    }

Output:

   t_str so far: 8
   ran_str so far:
   t_str so far: 88
   ran_str so far: 8
   t_str so far: 888
   ran_str so far: 88
   t_str so far: 8889
   ran_str so far: 889

If I initialize ran_str before t_str , then ran_str[] is not filled up as I'm strncat() t_str . Any reason why this might be happening?

This is because of several problems:

  1. t_str (and ran_str ) are only 1 byte long. (The null-terminator)
  2. There is no space in inbuf so the loop never ends.

Because ran_str is declared right after t_str it comes right after it in memory, so when strncat overflows the t_str buffer it writes into ran_str .

You need to allocate more memory for t_str (and probably ran_str ) and check you're not overflowing them. You also need to make sure you don't read past the end of inbuf , by checking if you haven't reached the null-terminator.

Culprit is your code which defines arrays:

char t_str[]="";
char ran_str[]="";

you should provide a length to both arrays. In above case I think t_str and ran_str both would get adjacent addresses. You can try this to confirm:

printf("%p %p\n", t_str, ran_str);

Fix it by using some length of array:

char t_str[10]="";
char ran_str[10]="";

When you do:

char t_str[] = "";

the array contains only 1 character, just enough room for the trailing null byte. When you then do:

strncat(t_str, &inbuf[pos], 1);

it copies one character into t_str (overwriting the null) and then appends a null byte to it. That means it's writing outside the bounds of the array, which is undefined behavior. In your implementation, it appears to be overwriting the beginning of ran_str .

The third argument to strncat should always be 1 less than the room remaining in the target array, to allow room for the null that will be appended. So it should be:

strncat(t_str, &inbuf[pos], sizeof(t_str)-strlen(t_str)-1);

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