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;
}
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;
}
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;
}