Thread: problem with malloc|free

  1. #1
    Registered User
    Join Date
    Dec 2015
    Posts
    6

    problem with malloc|free

    Hi all
    I'm new to this forums just recently started learning C. Can someone offer me some help with this code:
    Code:
    int main()
    {
        char *name=malloc(20*sizeof(char));         
        char *name2=malloc(20*sizeof(char));        
        char *name3=malloc(20*sizeof(char));        
        int i;
        int limit,limit2,limit3;
    
    
        printf("Enter name please:");               //collect names
        scanf("%s",name);
        printf("Enter other name please:");
        scanf("%s",name2);
        printf("Enter third name please:");
        scanf("%s",name3);
    
    
        limit=strlen(name);                         //calculate string lengths
        limit2=strlen(name2);
        limit3=strlen(name3);
    
    
        puts("\nFirst name was:");                  //print each character up until limit
        for(i=0;i<limit;i++)
            printf("%c",*(name+i));
        putchar('\n');
    
    
        puts("Second name was:");                   //print each character up until limit
        for(i=0;i<limit2;i++)
            printf("%c",*(name2+i));
        putchar('\n');
    
    
        puts("Third name was:");                    //print each character up until limit
        for(i=0;i<limit3;i++)
            printf("%c",*(name3+i));
        putchar('\n');
    
    
        printf("\nThe size of name is:%d\n",limit);     //demonstrate limits worked.
        printf("The size of name is:%d\n",limit2);
        printf("The size of name is:%d\n",limit3);
    
    
        free(name);             //call free function to release unused memory
        free(name2);
        free(name3);
    
    
        puts("\nFirst name was:");          //repeat of lines 23 - 38. print each string in sequence.
        for(i=0;i<limit;i++)
            printf("%c",*(name+i));
        putchar('\n');
    
    
        puts("Second name was:");
        for(i=0;i<limit2;i++)
            printf("%c",*(name2+i));
        putchar('\n');
    
    
        puts("Third name was:");
        for(i=0;i<limit3;i++)
            printf("%c",*(name3+i));
        putchar('\n');
    
    
        return 0;
    }
    The code works up until the point that I reprint the strings after using free. The first string outputs random characters but strings 2 and 3 both output fine. I can't understand this.

    Thank you for any help!
    Last edited by msnorm; 12-21-2015 at 08:09 PM.

  2. #2
    Registered User
    Join Date
    Dec 2015
    Posts
    6

  3. #3
    Registered User
    Join Date
    Jun 2011
    Posts
    4,509
    Well, once you free the memory, any access to that memory is invalid.

    Also, be careful when reading strings.

    Code:
    printf("Enter name please:");
    scanf("%s",name);
    printf("Enter other name please:");
    scanf("%s",name2);
    printf("Enter third name please:");
    scanf("%s",name3);
    There is nothing to prevent an overflow if the user enters too many characters.

    One way to limit this is to tell "scanf()" how many characters to read:

    Code:
    scanf("%19s",name);
    I personally prefer using "fgets()" to read a string from the user, as it easily allows you to specify how many characters to read from the indicated stream. There is a caveat with "fgets()", as it also stores the newline (if there is room), but removing this newline if present is trivial.

  4. #4
    Registered User
    Join Date
    Dec 2015
    Posts
    6
    Thank you for your help. That explains it. One thing though, is it luck then that the second two strings print correctly? I won't be doing this again in future I'm just curious to understand why they work but first one doesn't. o0.

    I understood free wrong, I thought it only released unused memory, ie the rest of the array that was not occupied with characters, so it was just a guess that where the string was could still be accessed without problems.
    Last edited by msnorm; 12-21-2015 at 08:24 PM.

  5. #5
    Registered User
    Join Date
    Jun 2011
    Posts
    4,509
    Quote Originally Posted by msnorm View Post
    One thing though, is it luck then that the second two strings print correctly?
    Yes, "luck" is the right word for that. Attempting to access free'd memory is referred to by the C standard as undefined behavior. That means anything can happen - there is no guarantee of behavior.

    Quote Originally Posted by C11-Draft
    J.2 Undefined behavior
    1 The behavior is undefined in the following circumstances:

    ...

    — The value of a pointer that refers to space deallocated by a call to the free or
    realloc function is used (7.22.3).
    Needless to say, any action that may result in undefined behavior should be avoided.

    Quote Originally Posted by msnorm View Post
    I understood free wrong, I thought it only released unused memory, ie the rest of the array that was not occupied with characters, so it was just a guess that where the string was could still be accessed without problems.
    C is very explicit. If you tell it to free memory, it will free that memory - it won't try to figure out exactly which bytes should be de-allocated. It is up to the programmer to ensure that their instructions are clear, specific, and precise.

  6. #6
    Registered User
    Join Date
    Dec 2015
    Posts
    6
    alright. It's a bit weird that no matter how many times I run the program with different strings input, always the same thing happens, first string outputs randomly and second two work fine. That's an odd type of randomness.

    It is up to the programmer to ensure that their instructions are clear, specific, and precise.
    Indeed, I'm only learning now that my instruction was not precise .

    Thanks for your help.
    Last edited by msnorm; 12-21-2015 at 09:03 PM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 16
    Last Post: 12-28-2012, 04:07 PM
  2. Malloc - Free giving double free or corruption error
    By andrew.bolster in forum C Programming
    Replies: 2
    Last Post: 11-02-2007, 06:22 AM
  3. Memory problem using malloc and free
    By zanyspydude in forum C Programming
    Replies: 2
    Last Post: 10-22-2007, 02:17 PM
  4. C array/malloc/free problem
    By Weasel in forum C Programming
    Replies: 6
    Last Post: 10-17-2007, 03:24 AM
  5. Malloc and Free.....
    By heljy in forum C Programming
    Replies: 5
    Last Post: 04-14-2002, 09:17 PM

Tags for this Thread