-1

I'm having a problem with c string, I want to keep address of original string aside and manipulate string using another c pointer, but it will give an segmentation fault when try to print that string using original or secondary pointer, however declaring string as character array does not present such fault. I don't to use array as well as I don't want to lose original address. Please point the problem.

/* segmentation fault when run */
char *string = "Hello World";
char *nick = string;
while(*nick)
    *nick++ = '0';
printf("%s\n", string);

/* display 000000000000 when run (wished result)*/
char array[] = "Hello World";
char *nick = array;
while(*nick)
    *nick++ = '0';
printf("%s\n", array);
David Ranieri
  • 39,972
  • 7
  • 52
  • 94
  • String literals like "Hello World" may be (and often are) allocated in read-only memory. If you want a modifiable string, declare an array, and use the string to initialize the array. – Lee Daniel Crocker Jul 31 '18 at 19:19
  • Lee Daniel Crocker , you mean there is no way to have a writeable string like mine *string? – Ahmad Raza Jul 31 '18 at 19:22
  • You would allocate a writable buffer, like in your second code sample, or with `malloc()`. – Davislor Jul 31 '18 at 20:37
  • @Davislor Thanks, I picked great idea of malloc and strcpy to achieve results. – Ahmad Raza Aug 01 '18 at 09:14
  • That works. You might also look at `strdup()`. – Davislor Aug 01 '18 at 17:35
  • @Davislor yes, I read that too. Things were solved instantly after knowing that "char * string" is equal to "const char * string" and that we can only change address of pointer, not the content of pointer. – Ahmad Raza Aug 03 '18 at 13:47

1 Answers1

1

The first code sample initializes your pointers to the start of a string constant. Modifying a string constant is undefined behavior.

In fact, you should never, ever write char *s = "hello world";. Always write const char *s or, better yet, const char* const s if it points to a string constant. The only reason you’re even allowed to have a pointer that isn’t const alias a string constant is for backward-compatibility with code written before the const keyword existed. There’s never any good reason to do it in new code.

The second code sample creates an array with static storage. Modifying that array is fine.

Davislor
  • 14,674
  • 2
  • 34
  • 49