今天用C语言写了一个小程序,但无法正确释放内存。程序如下:
#include <stdio.h>
#include <stdlib.h>
typedef struct stu {
char name;
int age;
char sex;
} stu;
stu get() {
stu* p = (stu*)malloc(sizeof(stu));
p->name = 'A';
return *p;
}
void freestu(stu p) {
free(&p);
}
int main() {
stu s1 = get();
printf("name:%c\n",s1.name);
freestu(s1);
return 0;
}
在Linux编译结果如下:
运行出现错误:
谁知道为什么?
求解。
stu s1已经分配内存了,get返回的是值,不是指针,因此你free的不是一个指针变量。
#include <stdio.h>
#include <stdlib.h>
typedef struct stu {
char name;
int age;
char sex;
} stu;
stu get(int i) {
stu* p = (stu*)malloc(sizeof(stu));
p->name = 'A'+i;
return *p;
}
int main() {
for(int i=0; i<10; i++) {
stu s1 = get(i);
printf("name:%c 0x%x 0x%x\n ",s1.name,&s1, &s1.name);
}
return 0;
}
运行结果。