Reputation: 756
Why is it that ...
char *dst = (char*) malloc(sizeof(char) * 11);
char *src = "ABCDEFGHIJKLMNOPQRSTUVQXYZ";
strncpy(dst, src, 10);
... works fine, but ...
char *dst = "ABCDEFGHIJ\0";
char *src = "ABCDEFGHIJKLMNOPQRSTUVQXYZ\0";
strncpy(dst, src, 10);
... or even ...
char *dst = "ABCDEFGHIJ\0";
char *src = "KLMNOPQRST\0";
strncpy(dst, src, 10);
gives segfault?
Also, how come this works:
char *dst = (char*) malloc(sizeof(char) * 10); // also works with 9
char *src = "ABCDEFGHIJKLMNOPQRSTUVQXYZ\0";
strncpy(dst, src, 10);
Copying 11 bytes into a pointer allocated with 10 bytes should in principle fail?
Upvotes: 0
Views: 97
Reputation: 86
The difference is that the string literals you initialized to the pointers dst and src in the later cases are stored in the data segment. A data segment is a portion of virtual address space of a program, which contains the global variables and static variables that are initialized by the programmer.
This segment can be further classified into initialized read-only area and initialized read-write area.
For instance the global string defined by
char s[] = “hello world”
in C and a C statement like int debug=1 outside the main (i.e. global) would be stored in initialized read-write area. And a global C statement like
const char* string = “hello world”
makes the string literal “hello world” to be stored in initialized read-only area and the character pointer variable string in initialized read-write area.
And in the above case...
char* dst = " ABCD........." ;
is equivalent to
const temp[]="ABCD......";
char* dst = &temp[0];
so the temp array which the dst is pointing will be stored in readonly memory and hence you cannot edit it...
Also in the final case even though you can copy 11 bytes into a pointer pointing to 10 bytes, you will encounter troubles during run time.... For eg: try freeing the pointer and you will face segmentation fault...( Undefined behaviour).
It is compiler dependent.
Upvotes: 1
Reputation: 409166
String literals may be stored in a read-only memory segment. You are not supposed to modify them.
Also, there's no checking for writing beyond bounds. Many of the security problems you hear of stem from the fact that there's a lot of code without any bounds checking.
Writing beyond the bounds of allocated memory, as well as attempting to modify a string literal or other read-only/constant data, leads to undefined behavior.
Upvotes: 6