-1
 char activeip[11]="0123456789";
char buffer[1001];
int MAX_SIZE = 1000;

printf("MAX_SIZE %d\n", MAX_SIZE);

strncpy(buffer, "string here.......  ",MAX_SIZE+1);
printf("MAX_SIZE %d\n", MAX_SIZE);

strncpy(&buffer[strlen(buffer)],activeip,MAX_SIZE+1 );
printf("MAX_SIZE %d\n", MAX_SIZE);

strncpy(&buffer[strlen(buffer)],"Long string here.....................................", MAX_SIZE+1);
printf("MAX_SIZE %d\n", MAX_SIZE);
puts(buffer);

as you can see, I initialized MAX_SIZE is 1000. when MAX_SIZE is not greater than buffer, MAX_SIZE become zero. the code's output like this:

MAX_SIZE 1000
MAX_SIZE 0
MAX_SIZE 0
string here.......  0123456789L

Process finished with exit code 0

how can a function(strncpy change to my local variable(MAX_SIZE) ? my compiler is minGW running on CLion thank you for your answer

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • 2
    It can change your local variable if your code has undefined behaviour, in this case because of a buffer overrun, which happens to run into the bytes representing the `MAX_SIZE`. Be sure to avoid UB :-) – underscore_d Aug 04 '20 at 10:42
  • 1
    @underscore_d thank you for helping :) It was the first time I saw a function affect my local variable. I was surprised. after that, I will pay attention to UB – kernel_panic Aug 04 '20 at 11:38

2 Answers2

1

These calls

strncpy(&buffer[strlen(buffer)],activeip,MAX_SIZE+1 );

and

strncpy(&buffer[strlen(buffer)],"Long string here.....................................", MAX_SIZE+1);

append the array pointed to by the first argument with MAX_SIZE + 1 minus the length of the copied string with zeroes.

According to the C Standard (7.23.2.4 The strncpy function)

3 If the array pointed to by s2 is a string that is shorter than n characters, null characters are appended to the copy in the array pointed to by s1, until n characters in all have been written.

So a memory beyond the array buffer is overwritten. You need to change the value of the third argument making it lesser (taking into account the length of the copied string and the used offset in the character array).

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • 1
    thank you for helping. I subtracted the length of the string from MAX_SIZE. then put it in the third argument. Now it works correctly! – kernel_panic Aug 04 '20 at 11:35
0

regarding statements like;

strncpy(&buffer[strlen(buffer)],activeip,MAX_SIZE+1 );

This not a good way to append that activeip string. Suggest:

strcat( buffer, activeip );

or

strncat( buffer, activeip, sizeof(buffer) - strlen buffer );
user3629249
  • 16,402
  • 1
  • 16
  • 17