我无法释放我使用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;
}
答案 0 :(得分:4)
您滥用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]);
}
答案 1 :(得分:2)
arrayOfStrngs[i]=(char*)malloc(strlen(gets(buffer)+1));//calculates string length and allocates appropriate memory
不应该是
arrayOfStrngs[i]=(char*)malloc(strlen(gets(buffer))+1);