c - 使用 free() 释放内存时遇到问题

标签 c malloc free memory-management

我在解除分配使用 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;
}

最佳答案

您误用了 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]);
}

关于c - 使用 free() 释放内存时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4538944/

相关文章:

c++ - 类破坏时的内存损坏(双重释放)

c - C 中的比较运算符返回什么?

c - 当子字符串与替换字符串相似时,如何在 C 中替换子字符串?

c - 这个 c 函数如何减少我的计数器?

c - 填充结构数组并在堆上分配内存

C - 字符数组似乎可以复制,但仅限于循环范围内

c - 如何防止 child 在 fork() 后干扰 parent 的标准输入

c - malloc 之后的空闲内存分配

c - free() 是否遵循指针?

我们可以使用之前释放的指针吗?