在我的C程序不能释放内存 [英] Can't deallocate memory in my C program
本文介绍了在我的C程序不能释放内存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要在下面的程序你的帮助释放内存。我想,你可以在主看到,但没有成功。无法获取该怎么做。
的#include<&stdio.h中GT;
#包括LT&;&stdlib.h中GT;
#包括LT&;&string.h中GT;typedef结构{
焦炭名[25];
焦炭街[25];
炭citystate [25];
炭拉链[6];
}学生; 学生的typedef * studinfo; / *函数原型* /
无效程序getinfo(学生*细节[],INT *); INT主要(无效)
{诠释计数= 0;
学生* studptr [49];是getinfo(studptr,和放大器;计数); / *调用程序getinfo函数来获取学生信息* /
/ * INT I = 0;
对于(I; I<计数;我++){ 免费(studptr [I] - >名);
免费(studptr [I] - >街道);
免费(studptr [I] - > citystate);
免费(studptr [I] - > ZIP);
} * / 返回0;
}
下面是一个函数来获取从该文件的信息。稍后我会利用这个信息的排序功能和显示功能来显示结果。从那以后,我应该释放的内存。
无效程序getinfo(学生*细节[],INT *计数)
{个char [100];
studinfo信息;/ *获取学生信息* /
而(得到(S)!= NULL){
信息=(studinfo)的malloc(sizeof的(学生));
的strcpy(信息 - >的名字,S);
得到(信息 - >街道);
得到(信息 - > citystate);
得到(信息 - > ZIP);
细节[(*计)++] =信息; / *增加指向下一个位置* / } / *结束while循环* / } / *是getinfo结束* /
解决方案
有三个问题你code:
- 您正试图
结构学生
的免费组件。由于这些组件阵列,与的malloc
分配的,你不能释放他们;你需要释放仅结构
本身。 - 您正在使用
获得
,这可能会导致缓冲区溢出。您应该使用与fgets
相反,通过缓冲区大小,和标准输入
为FILE *
参数。 - 您复制
S [100]
到信息 - >名称
。这有可能使缓冲区溢出,因为信息 - 方式>名称
只适合25个字符
一旦你解决这些问题,你的程序应该正常运行。
I need your help deallocating memory in below program. I tried as you can see in main, but no success. Can not get how to do it.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
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; i<count; i++) {
free(studptr[i]->name);
free(studptr[i]->street);
free(studptr[i]->citystate);
free(studptr[i]->zip);
} */
return 0;
}
Below is a function to get the info from the file. I will use this info later on in sort function and in display function to display the results. After that I should deallocate the memory.
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 */
解决方案
There are three problems with your code:
- You are trying to free components of
struct student
. Since these component arrays were not allocated withmalloc
, you cannot free them; you need to free only thestruct
itself. - You are using
gets
, which can cause buffer overruns. You should usefgets
instead, passing buffer size, andstdin
for theFILE*
parameter. - You copy
s[100]
intoinfo->name
. This can potentially overrun the buffer, becauseinfo->name
fits only 25 characters.
Once you fix these issues, your program should run correctly.
这篇关于在我的C程序不能释放内存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文