简体   繁体   中英

Trouble deallocating memory using free()

I have trouble deallocating memory that I allocated using malloc. The program runs fine until it the part where it's supposed to deallocate memory using free. Here the program freezes. So I was wondering what the problem could be since I'm just learning C. Syntactically the code seems correct so could it be that I need to delete all the stuff in that location before deallocating memory from that location or something else?

Here's the code.

// Program to accept and print out five strings
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define NOOFSTRINGS 5
#define BUFFSIZE 255

int main()
{
    char buffer[BUFFSIZE];//buffer to temporarily store strings input by user
    char *arrayOfStrngs[NOOFSTRINGS];
    int i;

    for(i=0; i<NOOFSTRINGS; i++)
    {
        printf("Enter string %d:\n",(i+1));
        arrayOfStrngs[i]=(char*)malloc(strlen(gets(buffer)+1));//calculates string length and allocates appropriate memory
        if( arrayOfStrngs[i] != NULL)//checking if memory allocation was successful
        {
            strcpy(arrayOfStrngs[i], buffer);//copies input string srom buffer to a storage loacation
        }
        else//prints error message and exits
        {
            printf("Debug: Dynamic memory allocation failed");
            exit (EXIT_FAILURE);
        }
    }

    printf("\nHere are the strings you typed in:\n");
    //outputting all the strings input by the user
    for(i=0; i<NOOFSTRINGS; i++)
    {
        puts(arrayOfStrngs[i]);
        printf("\n");
    }

    //Freeing up allocated memory
    for(i=0; i<NOOFSTRINGS; i++)
    {
        free(arrayOfStrngs[i]);
        if(arrayOfStrngs[i] != NULL)
        {
            printf("Debug: Memory deallocation failed");
            exit(EXIT_FAILURE);
        }
    }

    return 0;
}

You misuse strlen() and this results in buffer overrun:

arrayOfStrngs[i]=(char*)malloc(strlen(gets(buffer)+1)); //pointer from gets() is incremented and passed to strlen()  - that's wrong

should be

arrayOfStrngs[i]=(char*)malloc(strlen(gets(buffer))+1); //pointer from gets() is passed to strlen(), then returned value is incremented - correct

also free() doesn't change the pointer passed to it. So that

 char* originalValue = pointerToFree;
 free( pointerToFree ); 
 assert( pointerToFree == originalValue ); //condition will always hold true

and so in your code freeing memory should just be

//Freeing up allocated memory
for(i=0; i<NOOFSTRINGS; i++)
{
    free(arrayOfStrngs[i]);
}
arrayOfStrngs[i]=(char*)malloc(strlen(gets(buffer)+1));//calculates string length and allocates appropriate memory

那不是吗

arrayOfStrngs[i]=(char*)malloc(strlen(gets(buffer))+1);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM