Thread: malloc seg fault error

  1. #1
    Registered User
    Join Date
    Sep 2011
    Posts
    27

    malloc seg fault error

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    int main() {
      char** ptr=(char**)malloc(2*sizeof(char*));
      ptr[0]=(char*)malloc(10*sizeof(char));
      ptr[1]=(char*)malloc(10*sizeof(char));
      ptr[1]="goodnight";
      *(ptr[1])='p';
      puts(ptr[1]);
    }
    When I change letter g to p and try to output the string it gives seg fault error. Why? Thanks.

  2. #2
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    When you assign ptr[1] to a string literal you've done 2 things...

    1) you've leaked the memory you allocated to it
    2) you've connected it to text that cannot be changed.

    try...
    Code:
    strcy(ptr[1], "goodnight");
    and it will work.

    And...
    You need to free() the memory you allocated
    and return 0 from main before exiting.

  3. #3
    Registered User
    Join Date
    Sep 2011
    Posts
    27
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    int main() {
      char string[]="apple";
      char** ptr=(char**)malloc(2*sizeof(char*));
      ptr[1]=(char*)malloc(10*sizeof(char));
      ptr[1]=string;
      ptr[1][0]='p';
      puts(ptr[1]);
      puts(string); // ppple
    }
    If I assign char* pointer to char[] array it works.

  4. #4
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    It only appears to work...

    When you malloc ptr[1] you get a pointer to the memory you allocated
    When you assign ptr[1] to string, you abandon the pointer to the allocated memory and assign it to the string array.
    The pointer to the allocated memory is now lost... "leaked" in the vernacular, and that memory is locked to your program.

    So ptr[1] = string ... does not do what you think it does. It doesn't make a copy of the string.
    It becomes a pointer to the string array... so both string and ptr[1] aim at the same target.

    You can do ptr[1][0] = 'p' or you can do string[0] = 'p' ... and it will have the same effect because they are now cross connected.

    C is a language with absolutely no awareness of strings. What we do in their place is we manipuate arrays of characters. You absolutely cannot assign strings across the = sign like that... all you're doing is making a pointer assignment... not copying the string.

    If you doubt me... print out the address of ptr[1] right after allocating memory, then again after assigning it to string... you will have two completely different addresses... If you also print out the address of string, you will discover that it's the same as ptr[1] ... You aren't copying text, you are accidentally mainpulating pointers, and leaking memory to do it.

    Moreover; you are still not using free() to release your allocated memory and you are not returning an integer value from main... and yes, it does matter.
    Last edited by CommonTater; 12-24-2011 at 10:33 PM.

  5. #5
    Registered User
    Join Date
    Sep 2011
    Posts
    27
    Code:
    free(ptr[1]);
    This gives me either memory dump or seg fault. How to free ptr, ptr[0] and ptr[1] safely?

    OK memory leaked so it can't free it.

    This works.

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    int main() {
      char* ptr=(char*)malloc(10*sizeof(char));
      ptr[0]='p';
      ptr[1]='i';
      ptr[2]='e';
      ptr[3]='\0';
      puts(ptr);
      free(ptr);
    }
    Thanks comm.
    Last edited by gunitinug; 12-24-2011 at 10:50 PM.

  6. #6
    train spotter
    Join Date
    Aug 2001
    Location
    near a computer
    Posts
    3,868
    Opps....too late.....

    Define 'works'. Your code may show the expected result but is wrong (and only works because it is so simple).

    You have 'lost' (leaked the memory) the 10 x char block of memory you malloc'ed into ptr[1].

    Char arrays have special 'naming'.
    If you use the name of the char array, without an index (ie 'string' as opposed to 'string[0]' or 'string[9]') you are telling the complier to use the address of the first character in the 'string' array (ie 'string' == '&(string[0])')

    When you malloc 10 chars into ptr[1], you tell the compiler to;
    create a block of memory 10 chars wide
    set ptr[1][0] to the address of the first char in this new array

    So when you set ptr[1] == string [ ie ptr[1][0] == &(string[1][0]) ] you have lost the address of the first char (address) in this malloc'ed array (with no way to get it back).

    That is a memory leak and calling 'free(ptr[1]) will cause an exception (as you can not free memory you did not malloc, calloc, etc)

    Also 'string' is a local variable, so when the main function ends the complier deletes 'string'.
    In your code this is not a problem as the program ends.
    In most programs it would mean that ptr[1] now pointed at a block of memory that had been cleaned up (is not valid to use but may still hold the value 'ppple' for some undeterminate amount of time).
    This is known as a 'dangling pointer'.


    Code:
    //alloc the pointers of our main array
    char** ptr=(char**)malloc(2*sizeof(char*)); 
    //alloc array to hold the actual text  
    ptr[1]=(char*)malloc(10*sizeof(char));   
    //print text into our array
    strcpy(ptr[1], "apple"); //or sprintf(ptr[1], "apple"); etc
    //use / modify our array
    "Man alone suffers so excruciatingly in the world that he was compelled to invent laughter."
    Friedrich Nietzsche

    "I spent a lot of my money on booze, birds and fast cars......the rest I squandered."
    George Best

    "If you are going through hell....keep going."
    Winston Churchill

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Segmentation fault with Malloc
    By uniprog in forum C Programming
    Replies: 7
    Last Post: 12-02-2010, 10:22 AM
  2. malloc + segmentation fault
    By ch4 in forum C Programming
    Replies: 5
    Last Post: 04-07-2009, 03:46 PM
  3. unknown seg fault after malloc
    By seaking1 in forum C Programming
    Replies: 4
    Last Post: 02-25-2009, 07:51 PM
  4. Unknown Seg Fault and Malloc/Realloc Problems
    By DonFord81 in forum C Programming
    Replies: 6
    Last Post: 12-01-2008, 11:49 PM
  5. malloc segmentation fault
    By BharathKumar in forum C Programming
    Replies: 5
    Last Post: 06-27-2007, 02:53 AM