Reputation: 37
Here is the code
smem_dmp(char *name, char content[])
{
int i;
int len = strlen(content);
printf("%s\n\n", name);
for(i = 0; i < len; i++)
{
printf("%c\t%p\n", content[i], &content[i] );
}
printf("Done\n\n");
}
print_bar()
{
printf("********************************************************************\n");
}
int main(int argc, char *argv[])
{
char a[16];
char b[16];
strcpy(a, "abcdefghijklmnop");
printf("a = %s\nb = %s\n\n",a,b);
smem_dmp("A", a);
smem_dmp("B", b);
print_bar();
strcpy(b, "ABCDEFGHILKLMNOP");
printf("a = %s\nb = %s\n\n",a,b);
smem_dmp("A", a);
smem_dmp("B", b);
system("PAUSE");
return 0;
}
From looking at where a and b reside in memory I have worked out what is happening. The string copied to b is not null terminated. This is causing the contents of a to be removed because b is located (0028FF20) before a in memory (0028FF30).
What is happening? Does strcpy(b,"string") not stop until it has gone through all the memory on the stack frame variables? Sorry if I am not using the correct terminology. :)
Upvotes: 3
Views: 12970
Reputation: 183888
What is happening? Does
strcpy(b,"string")
not stop until it has gone through all the memory on the stack frame variables?
strcpy
copies bytes until it finds a 0-byte in the source. That is copied to the destination, and then strcpy
returns. (If the destination isn't big enough to hold the source including the 0-terminator, the behaviour is undefined, but unless you get a segmentation fault, that is what in practice you can rely on happening.)
So
strcpy(b, "ABCDEFGHILKLMNOP");
copies 17 bytes - the 16 letters and the 0-terminator - from the string literal to the array b
, which only contains 16 elements. That means the 0-terminator is written one element past the end of the array b
. In your situation, that is the first byte in a
, and the strcpy(b, "ABCDEFGHIJKLMNOP");
effectively makes a
contain an empty string.
Upvotes: 7
Reputation: 43518
the size of "abcdefghijklmnop"
is 16 and the size of your a
array is 16 it should be 17 (16 + 1 null terminator charachter)
Upvotes: 3