realloc二维结构数组

时间:2016-05-05 00:12:20

标签: c struct realloc

try { 
    FileInputStream fin = new FileInputStream(path + "myFile.xz");
    BufferedInputStream in = new BufferedInputStream(fin);
    FileOutputStream out = new FileOutputStream(des + "myDecompressed");
    XZInputStream xzIn = new XZInputStream(in);
    final byte[] buffer = new byte[8192];
    int n = 0;
    while (-1 != (n = xzIn.read(buffer))) {
        out.write(buffer, 0, n);
    } 
    out.close();
    xzIn.close();
}
catch(Exception e) { 
    Log.e("Decompress", "unzip", e); 

(我删节了我的代码)
我构建了二维结构数组,但这段代码不断给我一个错误,分段错误。

我认为问题出在这里。

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

struct a // linked list node
{
    char* st;
    struct a* pr;
    struct a* nx;
};

struct a* Init(char* w);
struct a* insert(struct a* old, char* w);

int main(void)
{
    struct a** A;
    A = (struct a**)malloc(sizeof(struct a*));
    A[0] = Init("HELLO");
    A[0] = insert(A[0], "WORLD");

    // I think the problem is here.
    A = (struct a**)realloc(A, 2*sizeof(struct a*));
    A[1] = Init("ELLO");
    A[1] = insert(A[1], "ORLD");

    free(A); 

    return 0;
}

struct a* Init(char* w)
{
    struct a* body = (struct a*)malloc(sizeof(struct a));
    struct a* tail = (struct a*)malloc(sizeof(struct a));

    body -> pr = NULL;
    body -> nx = tail;
    body -> st = w;

    tail -> pr = body;
    tail -> nx = NULL;
    tail -> st = NULL;

    return tail;
}

struct a* insert(struct a* old, char* w)
{
    struct a* tail = (struct a*)malloc(sizeof(struct a*));

    old -> nx = tail;
    old -> st = w;
    tail -> pr = old;
    tail -> nx = NULL;
    tail -> st = NULL;

    return tail;
} 

但我不知道为什么这是错的。 有什么想法吗?

提前致谢!

1 个答案:

答案 0 :(得分:1)

insert()函数中,您通过此行仅为一个指针分配了空间

struct a* tail = (struct a*)malloc(sizeof(struct a*));

另一方面,struct a有三个指针,因此它的大小将大于典型环境中一个指针的大小。

因此,会发生一些超出范围的访问。尝试像sizeof(struct a)函数中那样分配Init()