In the below program,
#include<stdio.h>
#include<stdlib.h>
int main(){
const char *str1 = "abc";
char *str2 = (char *)malloc(sizeof(char)*4);
str2= "def";
str2[1]='s';
printf("str2 is %s", str2);
}
Debugger :
(gdb) ptype str1
type = const char *
(gdb) ptype str2
type = char *
(gdb) n
7 str2[1]='s';
(gdb) n
Program received signal SIGSEGV, Segmentation fault.
0x00000000004005ab in main () at main.c:7
7 str2[1]='s';
(gdb)
SIGSEGV on str2[1] = 's';
As per my understanding, one cannot modify abc
pointed by st1
, due to declaration const char *st1 = "abc"
, where string literal is constant.
Why char *
type str2
does not allow modifying the elements? Is stringliteral def
also a constant string literal.
That's what happens:
str2
is allocated with malloc()
and points to the newly allocated buffer of 4 chars
You change the value (address) of str2
to the address of "def"
, which is read-only (think of it as a part of your program)
You try to change "def"
You are not able to free the memory because you actually lost the address of it when you assigned str2
to the address of "def"