1

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

Say I have s = " Hello". I want it to convert into s = "Hello".

This is what I have

# include <stdio.h>
# include <string.h>
main()
{
    char *s = " Hello";
    char *shift(char *, int);

    shift(s+1,-1);
    printf("%s", s);
}

char *shift (char *str, int units)
{
    if (units < 0)
    {
        for (; *str != '\0'; str++)
            *(str + units) = *str;
        *(str + units) = '\0';
        return str-strlen(str)-units;
    }

}

The program is terminating! Not even showing error. Where I am going wrong..

Most importantly, what makes this program to pass the control to OS to terminate?

Community
  • 1
  • 1
Surya
  • 4,824
  • 6
  • 38
  • 63

1 Answers1

4

You can not modify string literals. Also you never check that str + units is within the string i.e. it does not go out of the allocated memory of the string(assuming you passed a real string, not a string literal as argument).

Ivaylo Strandjev
  • 69,226
  • 18
  • 123
  • 176