/*Hi folks. Heres a very odd trouble ( for me at least) I was reading a book where it was stated that " char *ptr = "text"; " is an allowed declaration and that the compiler automatically allocates space for the string text and for the \0 terminating character ( true) . I decided to try it with strcpy(char *dest, const char *src) and there seems to be a problem. Whenever dest is a pointer declared as above theres a segmentation fault. I tried the code bellow which suffers from exactly the same. The problem seems to relly In the expression "while ( (*dest++ = *src++)!= '\0' )" . I tried all the combinations with strcpy, but only this one gave odd results. It seems that the compiler as some dificulties assigning *dest++ = *src++ when dest is a char *ptr = "kljdflg". But when src is this kind of pointer and dest is an array ( as so declared) , it works fine. Its not very usual to declare strings this way but its stated as ansi compliant, and the compiler silently accepts it without any warnings. The code is set to the particular combination where a SIGSEGV is generated dest=s1; /*char *s1 = "ldksj" src=string; /*char string[]= "dflkjg"*/
Can someone solve this mistery ? #include <stdlib.h> #include <stdio.h> /*#include <string.h>*/ // this is strcpy source code borrowed from string.h with another name char *strc(char *dest,const char *src) { char *tmp = dest; while ( (*dest++ = *src++)!= '\0' ); return tmp; } int main ( void ) { char *s1 = "frase_1"; char *s2 = "frase_2"; char string[] = "frase_3"; char *dest, *src; int i; //See if theres a terminating character int the string for( i = 0; i != strlen(string)+2; i++) printf( " s1[%x]=%d string[%x]=%d \n", s1+i, *(s1+i), string+i, string[i] ); //show s1 and string address printf( "s1 %x string %x", s1, string); fflush(stdout); //strcpy simulation dest=s1; src=string; //check if assignment is valid printf(" dest %x src %x ", dest, src ); fflush(stdout); //start copy while ( (*(dest++) = *(src++)) != '\0' ) { // want to see the address progression of dest and src printf( "\n dest[%x]= src[%x]= ", dest, src ); fflush( stdout ); } // the result printf( "\n ret dest address %x val %s \n", s1, s1 ); }