2012-10-08 96 views
1

我有一段代码存在问题,所以我尽可能地减少了它,事实上我找到了解决方案来解决我的问题,米几乎肯定有更好的解决方案,这就是为什么我要求帮助。在动态数组结构上使用realloc时发生Segfault错误

这里是不好的代码:

#include <stdio.h> 
#include <stdlib.h> 

typedef struct{ 
    int a; 
}my_struct; 

void tab_add(my_struct** tab, int i){ 
    *tab = (my_struct*)realloc(*tab, i+1); // Here's the realloc 

    printf("Adding struct number %d\n", i); 
    tab[i]->a = i*8; // Problem here, when accessing tab[i] the second time 
    printf("Struct added\n"); 
} 

int main(void){ 
    my_struct* tab = NULL; 

    tab_add(&tab, 0); 
    tab_add(&tab, 1); 
    tab_add(&tab, 2); 

    return 0; 
} 

的输出是:

添加结构编号0
STRUCT加入
添加结构数1
zsh的:分段故障./main

现在,这里是解决该问题的代码(但它创建了一个无用的变量...):

#include <stdio.h> 
#include <stdlib.h> 

typedef struct{ 
    int a; 
}my_struct; 

void tab_add(my_struct** tab, int i){ 
    *tab = (my_struct*)realloc(*tab, i+1); 

    printf("Adding struct number %d\n", i); 
    my_struct st; // Useless variable created 
    st.a = i*8; 
    (*tab)[i] = st; 
    printf("Struct added\n"); 
} 

int main(void){ 
    my_struct* tab = NULL; 

    tab_add(&tab, 0); 
    tab_add(&tab, 1); 
    tab_add(&tab, 2); 

    return 0; 
} 

它的输出是正确的:

添加结构数0
结构添加
加入结构数1
STRUCT加入
添加结构数2
STRUCT加入

感谢您的阅读:)

回答

2

您应该使用

(*tab)[i].a = i*8; 

访问字段a

+0

它的工作原理!谢谢。我真的认为编译器正在用(* tab)[x] .x代替tab [x] - > b!它究竟发生了什么变化? – user1729422

+0

'tab [x] - > b'是'(* tab [x])。b'不是'(* tab)[x] .b' –

+0

好的,谢谢:) – user1729422

1

realloc手册页。第二个参数是你想要分配的数据的大小;我想你是在传递一个数组索引。

的代码应该是理想的形式

my_struct* tmp = realloc(*tab, sizeof(my_struct) * (i+1)); 
if (tmp == NULL) { 
    /* error handling goes here */ 
else { 
    *tab = tmp; 
} 

,以应对realloc的失败并返回NULL。如果你想摆脱ST的

(*tab)[i].a = i*8; 

1

这是为使这一分配新建分配FY一样简单。

0

不知道你在这里试图达到什么目的。根据realloc文档,尽可能增加分配空间的大小,如果不是,它就像free和malloc一样。所以在你的情况下,如果你想为结构分配一个空间,每次都是一样的。但根据代码,它是第一次0字节,它会尝试释放(分配的内存是没有的,seg故障也是如此)。

另外你说的是修复似乎不是一个修复。它会在稍后的某个时刻死亡。因为堆栈在第一次调用时已经损坏。