Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

segmentation fault in c program

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

like image 414
codeomnitrix Avatar asked Dec 11 '10 12:12

codeomnitrix


1 Answers

char *p = "Hello world"; *(p+1) = 'l';

Modiying the content of a string literal (i.e "Hello World" in your code) is Undefined Behavior.

ISO C99 (Section 6.4.5/6)

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.

Try using array of characters.

char p[] = "Hello World";
p[1] = 'l'; 

EDIT

Your modified code

#include<stdio.h>
#include<stdlib.h>
int main()
{
   char *p = malloc(sizeof(char)*100);
   p = "Hello world"; // p now points to the string literal, access to the dynamically allocated memory is lost.
   *(p+1) = 'l'; // UB as said before edits
   printf("%s", p);
   free(p); //disaster
   return 0;
}

invokes Undefined Behaviour as well because you are trying to deallocate the section of memory (using free) which has not been allocated using malloc

like image 178
Prasoon Saurav Avatar answered Sep 28 '22 20:09

Prasoon Saurav