【发布时间】:2012-12-07 12:35:40
【问题描述】:
我试图了解以下内容,这 3 个函数调用如何正常工作, 我不确定它在内部是如何工作的,我可以很好地理解第一个,但是第二次我用结构的 sizeof 调用 malloc 然后打印它,第三次我用结构指针的 sizeof 调用 malloc 和也打印出来。两者如何可以毫无问题地工作? 第二个 malloc 分配的大小为 2*2*int=16 字节,第三个 malloc 分配的大小为 2*pointer=8。 而且我在尝试释放 pt2 时得到核心转储,这是在 Linux 上使用 C 和 gcc
#include<stdio.h>
#include<stdlib.h>
struct test{
int field1;
int field2;
};
struct test func(int a, int b) {
struct test t;
t.field1 = a;
t.field2 = b;
return t;
}
int main()
{
struct test t;
struct test pt[2];
pt[0] = func(1,1);
pt[1] = func(2,2);
printf("%d %d\n", pt[0].field1,pt[0].field2);
printf("%d %d\n", pt[1].field1,pt[1].field2);
printf("\n");
struct test *pt1;
pt1 = malloc(sizeof(struct test) * 2);
pt1[0] = func(2,2);
pt1[1] = func(3,3);
printf("%d %d\n", pt1[0].field1,pt1[0].field2);
printf("%d %d\n", pt1[1].field1,pt1[1].field2);
printf("\n");
struct test *pt2;
pt2 = malloc(sizeof(struct test*) * 2);
pt2[0] = func(4,4);
pt2[1] = func(5,5);
printf("%d %d\n", pt2[0].field1,pt2[0].field2);
printf("%d %d\n", pt2[1].field1,pt2[1].field2);
free(pt1);
free(pt2);// I'm getting core dump when trying to free pt2
}
输出低于
1 1
2 2
2 2
3 3
4 4
5 5
【问题讨论】: