third argument of the strncpy changes my local variable

386 Views Asked by At
 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

2

There are 2 best solutions below

1
Vlad from Moscow On

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

0
user3629249 On

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 );