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
These calls
and
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)
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).