无法在我的C程序中释放内存
我需要你帮助在下面的程序中释放内存。 我试过,你可以看到主要,但没有成功。 无法得到如何做到这一点。
#include #include #include typedef struct{ char name[25]; char street[25]; char citystate[25]; char zip[6]; }student; typedef student *studinfo; /*function prototypes*/ void getinfo(student *details[], int *); int main(void) { int count = 0; student *studptr[49]; getinfo(studptr, &count);/*call getinfo function to get student info*/ /*int i = 0; for (i; iname); free(studptr[i]->street); free(studptr[i]->citystate); free(studptr[i]->zip); } */ return 0; }
以下是从文件中获取信息的function。 稍后我将在sort函数和display函数中使用此信息来显示结果。 之后我应该释放内存。
void getinfo(student *details[], int *count) { char s[100]; studinfo info; /*Get student information*/ while (gets(s) != NULL) { info = (studinfo)malloc(sizeof(student)); strcpy(info->name, s); gets(info->street); gets(info->citystate); gets(info->zip); details[(*count)++] = info; /*Increase the pointer to next position*/ } /* End of while loop*/ } /* End of getinfo */
您的代码有三个问题:
- 您正在尝试释放
struct student
组件。 由于这些组件数组未分配malloc
,因此无法释放它们; 你只需要释放struct
本身。 - 您正在使用
gets
,这可能导致缓冲区溢出。 您应该使用fgets
代替,传递缓冲区大小和stdin
作为FILE*
参数。 - 您将
s[100]
复制到info->name
。 这可能会超出缓冲区,因为info->name
只能info->name
25个字符。
解决这些问题后,您的程序应该正确运行。
它应该是:
int i; for (i = 0; i < count; i++) { free(studptr[i]); }
由于您将每个student
分配为一个块,因此您可以以相同的方式释放它们。