-1

This following code gives Segmentation fault:

#include <stdio.h>

int main()
{
    char* str = "hello world";
    str[0] = 'H'; // it is throwing segmentation fault.
    
    printf("%s",str);

    return 0;
}
mch
  • 9,424
  • 2
  • 28
  • 42
  • You're trying to modify a string literal, which you can't do. One alternative is to make `str` be defined as `char str[]`. – Thomas Jager Mar 30 '22 at 12:01

1 Answers1

4

char pointers defined with an initialization value goes into a read-only segment. To modify them later in your code you need to make it to store on heap memory using malloc() or calloc() functions, or define them as arrays. Must Read

Cannot be changed:

char *ptr1 = "Hello, World!";

Can be changed:

char ptr2[] = "Hello, World!";

Example for Heap-Memory:

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

int main(void){
    char *str = calloc(14, sizeof(char));
    strcpy(str, "Hello, World!");
    
    printf("Before: %s\n", str);
    str[0] = 'Q';
    printf("After: %s\n", str);

    free(str); // heap-allocated memory must be freed
    return EXIT_SUCCESS;
}

Example of Array (stack allocated memory):

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

int main(void){
    char str[14] = {}; // decayed to pointer, but `sizeof()` operator treats this as an array in C
    strcpy(str, "Hello, World!");
    
    printf("Before: %s\n", str);
    str[0] = 'Q';
    printf("After: %s\n", str);
    
    return EXIT_SUCCESS;
}
Darth-CodeX
  • 2,166
  • 1
  • 6
  • 23