typedef struct{
int number;
char name[100];
} Apple
typedef struct{
Apple *apple;
int bit[2];
} AppleArray;
int main(){
AppleArray *aArray;
loadApple(&aArray);
}
loadApple(AppleArray **aArray){
*aArray = NULL;
for(i=0; i<100; i++){
*aArray = realloc(*aArray, (i+1) * sizeof(AppleArray));
/*SEGFAULT here*/
aArray[i]->apple = NULL;
for(j=0; j<2; j++){
aArray[i]->apple = realloc(aArray[i]->apple, sizeof(Apple) * (j+1))
}
}
}
我希望拥有特定尺寸的AppleArray。每个AppleArray都有两个Apple。但是,当我为aArray [i] - &gt; apple指定NULL时,我得到段错误。有什么问题?
编辑:
loadApple(AppleArray **aArray){
*aArray = malloc(100 * sizeof(AppleArray));
for(i=0; i<100; i++){
/*SEGFAULT here*/
aArray[i]->apple = NULL;
for(j=0; j<2; j++){
aArray[i]->apple = realloc(aArray[i]->apple, sizeof(Apple) * (j+1))
}
}
}
答案 0 :(得分:1)
您只能通过先前的内存分配函数(如realloc()
或malloc()
)返回给您的地址调用calloc()
,否则会为您提供未定义的行为
C99标准7.20.3.4-3:重新分配功能:
void *realloc(void *ptr, size_t size);
如果
ptr
是空指针,则realloc函数的行为类似于malloc函数 指定大小。否则,如果ptr与先前由内存返回的指针不匹配 管理功能,或者如果通过调用free或者释放空间 realloc函数,行为未定义。
答案 1 :(得分:1)
除了Als上面提到的,你也有一个数组越界读取问题,因为在你的循环之后,我的值将是100并且你试图访问aArray[100]
而在你的逻辑中(虽然不正确)你只会在aArray[99]
之前分配内存。
您的loadApple函数可以重写如下:
loadApple(AppleArray **aArray)
{
*aArray = NULL;
*aArray = malloc(100 * sizeof(AppleArray));
//I have shown index as 0 here just as an example.
(*aArray)[0].apple = NULL;
(*aArray)[0].apple = malloc(2 * sizeof(Apple));
}
此代码也应该提供与代码逻辑相同的行为。
答案 2 :(得分:0)
<pre>
#include "stdio.h"
#include "stdlib.h"
#define MAX_SIZE 5
#define NAME_SIZE 100
#define APPLE_NUM 2
typedef struct
{
int number;
char name[NAME_SIZE];
}Apple;
typedef struct
{
Apple* apple;
int bit[2];
}AppleArray;
void printApple(AppleArray** aArray)
{
int i;
for (i = 0; i < MAX_SIZE; ++i)
{
fprintf(stderr, "%4d: bit[0] = %d, bit[1] = %d\n", i, (*aArray + i)->bit[0], (*aArray + i)->bit[1]);
int j;
for (j = 0; j < APPLE_NUM; ++j)
{
fprintf(stderr, "\tapple[%d]: number = %d, name = %s\n",
j,
(*aArray + i)->apple[j].number,
(*aArray + i)->apple[j].name);
}
printf("\n");
}
}
void loadApple(AppleArray **aArray)
{
*aArray = NULL;
int i;
for(i = 0; i < MAX_SIZE; i++)
{
AppleArray* tmp = (AppleArray*)realloc(*aArray, (i+1) * sizeof(AppleArray));
if (tmp != NULL)
{
*aArray = tmp;
}
else
{
//error
free(*aArray);
*aArray = NULL;
exit(0);
}
/*SEGFAULT here*/
//aArray[i]->apple = NULL;
(*aArray + i)->apple = NULL;
(*aArray + i)->bit[0] = i;
(*aArray + i)->bit[1] = i + 1;
/*
int j;
for (j = 0; j < 2; j++)
{
(*aArray + i)->apple = realloc(aArray[i]->apple, sizeof(Apple) * (j+1));
}
*/
(*aArray + i)->apple = (Apple*)realloc(NULL, sizeof(Apple) * APPLE_NUM);
int j;
for (j = 0; j < APPLE_NUM; ++j)
{
(*aArray + i)->apple[j].number = j;
snprintf( (*aArray + i)->apple[j].name, NAME_SIZE, "apple_%d_%d", i, j);
}
}//for
}
void destroyApple(AppleArray* thiz)
{
if (thiz == NULL)
{
return;
}
int i;
for (i = 0; i < MAX_SIZE; ++i)
{
free(thiz[i].apple);
thiz[i].apple = NULL;
}
free(thiz);
}
int main()
{
AppleArray *aArray;
loadApple(&aArray);
printApple(&aArray);
destroyApple(aArray);
return 0;
}