我有一個問題,自我參照構造調用的realloc。當我運行這個程序時,我得到錯誤*** Error in ...: realloc(): invalid next size: 0x0000000000602160 ***
。我想這個問題與最後一行有關,因爲如果我評論它,程序運行沒有任何問題。Ç - 自引用的結構和realloc
這是代碼最小的(不)工作片:
#include <string.h>
#include <stdlib.h>
typedef struct structure {
int connections;
struct structure *links;
} structure;
int main(int argc, char *argv[]) {
int struct_count;
int i, from, to, offset;
structure *structs;
struct_count = 2;
structs = malloc(sizeof(structure) * struct_count);
memset(structs, 0, sizeof(structure) * struct_count);
for(i = 0; i < struct_count; i++) {
structs[i].links = malloc(1);
structs[i].connections = 0;
}
for(i = 0; i < 100; i++) {
from = 0;
to = 1;
offset = structs[from].connections++;
structs[from].links = realloc(structs[from].links, sizeof(int) * (offset + 1));
structs[from].links[offset] = structs[to]; // This is the problematic line - why?
}
}
我的問題:什麼是錯的代碼?
'的malloc(1)'是不夠的的指針,這個'結構[從] .links = realloc的(結構[從] .links,的sizeof(int)的*(偏移+ 1));'是危險的, 'realloc()'可能返回NULL,並且先前的poitner將會消失,從而導致內存泄漏。 –
爲什麼''realloc'中的sizeof(int)'?更改爲'sizeof(structure)' –
「下一個大小無效」不可避免地指出在解除分配或重新分配之前發生的一些錯誤。運行valgrind查看問題發生的位置。 – dasblinkenlight