-6

I am trying to assign a character using pointer but it doesn't do.

Will somebody please explain why following program stops working ?

#include <string.h>

int main(void) {
  char *s = "modifying...";
  // char s2[] = {'m','o','d','i','f','y','i','n','g','.','.','.',NULL};
  // s = s2;
  puts(s);
  *s = 'M'; // Here the program stops working
  puts(s);
  return 0;
}
Ankur
  • 149
  • 7

3 Answers3

1

You may not change a string literal that way.

https://stackoverflow.com/a/17507772/234307

"A C string literal creates an anonymous array of char. Any attempt to modify that array has undefined behavior." - Keith Thompson

Community
  • 1
  • 1
jn1kk
  • 5,012
  • 2
  • 45
  • 72
  • If you can answer a question by linking to an answer to an other question, it is a sign that perhaps the first one should be closed as a duplicate rather than answered. – Pascal Cuoq Sep 02 '14 at 15:16
0

Though string literals in C have types of non-const character arrays nevertheless they are immutable. You may not change string literals. Use instead

char s[] = "modifying...";
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • Pedantry: They aren't in no way guaranteed to be immutable. C standard does not require it, and at least *gcc* has option to make them writable. – hyde Sep 02 '14 at 14:43
  • @hyde There is clear written in the C Standard "The same considerations apply to each element of the sequence in a string literal as if it were in an integer character .constant" – Vlad from Moscow Sep 02 '14 at 14:45
  • A quick googling seems to indicate, that that refers to just syntax, not actual data. If it referred to data, how could you take an address of an element in a string literal, if it really were as taking address of an integer char constant? – hyde Sep 02 '14 at 14:56
  • @hyde I am sorry. The correct quote will be "If the program attempts to modify such an array, the behavior is undefined." – Vlad from Moscow Sep 02 '14 at 15:12
0

The string literal itself is located in memory outside of the function. What you'd want to do is allocate a buffer for a modifiable string...

char *pszLiteral = "literal";
char *pszBuffer = (char *)malloc(strlen(pszLiteral) + 1);
strcpy(pszBuffer, pszLiteral); // copy the literal value located at pszLiteral to the buffer pszBuffer, which is modifiable (located on heap)
*pszBuffer = 'L'; // or pszBuffer[0] = 'L';
puts(pszBuffer);
free(pszBuffer);

or you could use a static buffer located on the stack instead of the heap

char *pszLiteral = "literal";
char pszLocal[20];
strcpy(pszLocal, pszLiteral);
*pszLocal = 'L'; // or pszLocal[0] = 'L';
puts(pszLocal);