0

This is my program and it is seg faulting when i try to do s[0] = s[1]. I don't understand why this wouldn't work as all i am doing is taking value in s[1] and putting it in s[0].

#include<stdio.h>

void main() {
  char x;
  char *s="stackoverflow";

  s[0] = s[1];  // it is segfaulting here 
  x = s[0];  //this works though 
  printf("this is: %s\n",s);
}

i am compiling using gcc filename.c and running it using ./a.out in ubuntu terminal.

Thank you.

hunterr986
  • 43
  • 1
  • 10

3 Answers3

2

When you do: char *s="stackoverflow"; then s is a pointer that points to a memory that is in the code part, so you can't change it. Because it's read-only, you're getting segmentation fault at runtime (if you used the const keyword, you would get a compilation error, which is better.. So it's recommended to use const if you don't want to make changes on strings).

If you do char s[]="stackoverflow"; then s is an array of chars that are on the stack, so you can change it.

Maroun
  • 94,125
  • 30
  • 188
  • 241
  • This is to say that the string is not defined on the heap as it would be had you malloc'd a buffer and then attempted to modify on the heap, which is legal. – jbh Mar 13 '13 at 18:05
  • Whether it's read only or not will depend on the implementation. – teppic Mar 13 '13 at 18:23
1

You should not attempt to change a string literal. If you want to modify the value, make a copy using strcpy for instance.

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

Change declaration of variable:

char s[] = "stackoverflow";

will remove the problem you have, as variable will have storage allocated on entering the scope and initialized with the data given.

Valeri Atamaniouk
  • 5,125
  • 2
  • 16
  • 18