我正在尝试分配一个内存块,并存储一个结构列表,而无需为每个结构使用多个 mallocs...这只是一个通用示例,我没有之前使用的原始代码,但是这是一般的想法,但我的问题是当我的代码的其他部分在 InitPoints() 函数调用之后执行时,我得到了堆损坏。我不知道我的代码的哪一部分是非法的,但我怀疑它在 InitPoints() 函数的 for 循环中。我正在尝试将其用作表,然后如果内存不足,我可以创建额外的定义大小的表并将它们链接在一起……如果有任何意义的话,有点像动态扩展数组。
typedef struct Tb{
POINT points;
POINT *next;
} TABLE;
typedef struct Pt{
int x;
int y;
}POINT;
POINT *mypoints;
int main() {
int size = 10;
int i = 0;
mypoints = InitPoints(size);
for(i=0; i < size; i++)
{
printf("mypoint [%d] = (%d,%d)\n",i, mypoints->x, mypoints->y);
mypoints = mypoints + sizeof(POINT);
}
// some other code...
// i.e. createThread(....)
return 0;
}
POINT* InitPoints(int size)
{
POINT *tmp;
POINT *orig;
int a = 10;
int b = 1000;
orig = (POINT*) malloc (sizeof(POINT) * size);
if(orig == NULL)
return NULL;
tmp = orig;
for (i = 0; i < size; i++)
{
tmp->x = a++;
tmp->y = b++;
tmp = tmp + sizeof(POINT);
}
return orig;
}
最佳答案
这是错误的:
mypoints = mypoints + sizeof(POINT);
你应该复习一下 C 中的指针算法。只需使用:
mypoints += 1; /* or something similar */
(你的InitPoints函数也有类似的问题)
这是一个引用:
关于c - 将 malloc 用于结构 block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3106828/