【发布时间】:2011-05-31 03:37:02
【问题描述】:
我无法释放使用 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;
}
【问题讨论】:
-
经典风格错误。将代码放在多行中不会花费更多。此外,gets() 可以返回 NULL,kaboom。
-
!!!永远不要使用
gets()。曾经。顺便说一句,您的错误报告是错误的:调用free不会影响您传入的指针的值 - 这在 C 中是 不可能,无需添加另一层间接,free没有。即使内存被成功释放,你的程序也认为没有。
标签: c malloc free memory-management