0

The code is self-explanatory, but it gives me segmentation fault, why? :\

#include <stdio.h>
int main(void)
{
    char *c = "Hella";
    *(c+4) = 'o';
    printf("%s\n",c);
}
DarioDP
  • 627
  • 2
  • 9
  • 24

5 Answers5

9

How to avoid it?

Don't modify a string literal!

char *c = "Hella";

Declares a pointer c to a string literal "Hella" stored in implementation defined read only memory.
You are not allowed to modify this literal. An attempt to do so results in Undefined Behavior.

You are lucky that your program crashes, an Undefined Behavior does not always result in a crash but may cause your program to behave weirdly in any possible way.

What you need here is an array:

char c[] = "Hella";

Good Read:
What is the difference between char a[] = ?string?; and char *p = ?string?;?

Community
  • 1
  • 1
Alok Save
  • 202,538
  • 53
  • 430
  • 533
1

Put your string into an array allocated onto the stack:

char c[] = "Hella";

Because as said, string literals are usually read-only.

Geoffrey R.
  • 1,907
  • 1
  • 19
  • 32
0

the way you create c it points to a string literal. You can not modify it's contents. If you want to be able to do that use:

char c[6] = "Hella";
c[4] = o;

Or use a dynamically allocated char array.

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

You are trying to overwrite a literal. Really your code should read:

const char *c = "Hella";

Which kinda explains what is going on.

To overwrite your own memory:

char c[] = "Hella";

is safer.

cdarke
  • 42,728
  • 8
  • 80
  • 84
0

You can not modify strings that are defined in code. Use strdup if you want to modify them.

#include <stdio.h>
int main(void)
{
    char *c = strdup("Hella");
    *(c+4) = 'o';
    printf("%s\n",c);
    free(c);
}
Geoffrey R.
  • 1,907
  • 1
  • 19
  • 32
Dariusz
  • 21,561
  • 9
  • 74
  • 114
  • @Geoffrey. It is not correct to edit the sense of a post. You can edit only the form. Language, format etc. You can propose the change in a comment though. – Gangnus Jan 09 '13 at 16:15
  • Yes, the change was correct, but according to rules we should use edit for the form only, not the content! Geoffrey should propose the content change by the means of a comment. – Gangnus Jan 09 '13 at 21:48
  • Huh really sorry for that Gangnus this should never happen again, I'll carry it out. Thanks! – Geoffrey R. Jan 09 '13 at 21:58