首页 文章

无法使用free()释放内存

提问于
浏览
1

我无法释放我使用malloc分配的内存 . 程序运行正常,直到它应该使用free释放内存的部分 . 程序冻结了 . 所以我想知道问题是什么,因为我只是在学习C.语法上代码似乎是正确的,所以我需要删除该位置的所有东西,然后从该位置或其他地方释放内存?

这是代码 .

// 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;
}

2 回答

  • 2

    您滥用 strlen() ,这会导致缓冲区溢出:

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

    应该

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

    free() 不会改变传递给它的指针 . 以便

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

    所以在你的代码中释放内存应该只是

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

    不应该这样

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

相关问题