[英]Trouble deallocating memory using free()
我无法解除分配使用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]);
}
arrayOfStrngs[i]=(char*)malloc(strlen(gets(buffer)+1));//calculates string length and allocates appropriate memory
那不是吗
arrayOfStrngs[i]=(char*)malloc(strlen(gets(buffer))+1);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.