1

Possible Duplicate:
Why do I get a segmentation fault when writing to a string?

Here is a small function, was testing something so wrote it. Here i tried to increment a character value of the string literal when i tried doing so i got a segmentation fault. Can you please tell what i am doing wrong here

#include <stdio.h>
int input_string(char *str)
{
  printf("%s\n", str);
  printf("%c\n", *str);
  printf("%c\n", (*str)++); // I get a segmentation fault here, cant i increment the value like this ?
}
void main()
{
  char *str = "andrew";
  input_string(str);
}
Community
  • 1
  • 1
Manu
  • 5,534
  • 6
  • 32
  • 42

2 Answers2

2

What this char *str = "andrew"; does is create a pointer to a string that MAY be located on .text (where the executable code resides) and trying to modify it is undefined behavior.

Change it for this:

char str[] = "andrew";

It will make a copy of the string in a stack allocated buffer that you can safely modify.

imreal
  • 10,178
  • 2
  • 32
  • 48
  • So any such initialization like char *ptr = "Stack" to a char ptr declaration, will be like a const char *ptr = "stack"; – Manu Jan 15 '13 at 02:33
  • Yes, as a matter of fact when you do something like that, you should declare it as `const` to prevent these kinds of errors. – imreal Jan 15 '13 at 02:34
0

This:

char *str = "andrew";

means what str points to a constant string literal. You will get undefined behavior if you try to change it.

If you want to perform string manipulation, define a character array.

Iceman
  • 4,202
  • 7
  • 26
  • 39