0
#include <stdio.h>
#include <stdlib.h>

int main() {
    char *str="hello";
    str[0]='H';
    return 0;
}

If I use an array I can do use subscript to assign the first character. What's different about using a char pointer here that causes a segmentation fault?

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
sudeepdino008
  • 3,194
  • 5
  • 39
  • 73

2 Answers2

3

In this code snippet

char *str="hello";
str[0]='H';

you are trying to change a string literal pointed to by the pointer str. Any attempt to change a string literal results in undefined behavior.

From the C Standard (6.4.5 String literals)

7 It is unspecified whether these arrays are distinct provided their elements have the appropriate values. If the program attempts to modify such an array, the behavior is undefined.

So though in C opposite to C++ string literals have types of non-constant arrays it is always better to declare pointers to string literals with the qualifier const.

const char *str="hello";

You could declare a character array initialized by the string literal and change the array itself like

char str[] ="hello";
str[0]='H';
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
0

okay, I got the answer from this wiki - https://en.wikipedia.org/wiki/Segmentation_fault#Writing_to_read-only_memory

The char pointer declared like that writes to a read-only segment of the process, editing that gives a segmentation fault (specifically SEGV_ACCERR which is defined as invalid permissions for mapped object (see here)

An array on the other hand similarly allocated will be done so on the stack and so can be edited.

sudeepdino008
  • 3,194
  • 5
  • 39
  • 73