gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 00:55:23 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com