c - Predefined string segfaults when copied to by strncpy() -


why ...

char *dst = (char*) malloc(sizeof(char) * 11); char *src = "abcdefghijklmnopqrstuvqxyz"; strncpy(dst, src, 10); 

... works fine, ...

char *dst = "abcdefghij\0"; char *src = "abcdefghijklmnopqrstuvqxyz\0"; strncpy(dst, src, 10); 

... or ...

char *dst = "abcdefghij\0"; char *src = "klmnopqrst\0"; strncpy(dst, src, 10); 

gives segfault?

also, how come works:

char *dst = (char*) malloc(sizeof(char) * 10); // works 9 char *src = "abcdefghijklmnopqrstuvqxyz\0"; strncpy(dst, src, 10); 

copying 11 bytes pointer allocated 10 bytes should in principle fail?

the difference string literals initialized pointers dst , src in later cases stored in data segment. data segment portion of virtual address space of program, contains global variables , static variables initialized programmer.

this segment can further classified initialized read-only area , initialized read-write area.

for instance global string defined

char s[] = “hello world”  

in c , c statement int debug=1 outside main (i.e. global) stored in initialized read-write area. , global c statement

const char* string = “hello world” 

makes string literal “hello world” stored in initialized read-only area , character pointer variable string in initialized read-write area.

and in above case...

char* dst = " abcd........." ; 

is equivalent

const temp[]="abcd......";  char* dst = &temp[0]; 

so temp array dst pointing stored in readonly memory , hence cannot edit it...

also in final case though can copy 11 bytes pointer pointing 10 bytes, encounter troubles during run time.... eg: try freeing pointer , face segmentation fault...( undefined behaviour).

it compiler dependent.


Comments

Popular posts from this blog

android - MPAndroidChart - How to add Annotations or images to the chart -

javascript - Add class to another page attribute using URL id - Jquery -

firefox - Where is 'webgl.osmesalib' parameter? -