just for testing i had created the following code:
#include<stdio.h>
int main(){
char *p = "Hello world";
*(p+1) = 'l';
printf("%s", p);
return 0;
}
But when i ran this over my “gcc” compiler under ubuntu 10.04 I got:
Segmentation fault
So can anyone explain this why this happened.
#include<stdio.h>
#include<stdlib.h>
int main(){
char *p = malloc(sizeof(char)*100);
p = "Hello world";
*(p+1) = 'l';
printf("%s", p);
free(p);
return 0;
}
this also cause a segmentation fault
Thanks in Advance
Modiying the content of a string literal (i.e “Hello World” in your code) is Undefined Behavior.
ISO C99 (Section 6.4.5/6)
Try using array of characters.
EDIT
Your modified code
invokes Undefined Behaviour as well because you are trying to deallocate the section of memory (using
free) which has not been allocated usingmalloc