开发者

Seemingly random segfault

I'm trying to achieve a dynamic two dimensional array in C.

Whenever the program is trying to access a value in the array I'm checking whether or not the array is large enough. If it isn't more storage should be allocated. The code below checks whether or not the array has enough columns and if it doesn't it reallocates new memory.

unsigned long cnt; // y is the element we are trying to access, playfieldsize stores the size of the array
if (y >= playfieldsize.y) { // if the array isn't large enough more data should be allocated
    char **tmp;
    unsigned long cnt;
    cnt = playfieldsize.y; // stores the old size of the array
    playfieldsize.y += (y - playfieldsize.y) + INCREASE; // the new array size
    if (tmp = realloc(playfield, playfieldsize.y * sizeof(char *))) { // if storage can be allocated for the new size
        playfield = tmp;
        for (; cnt<playfieldsize.y; cnt++) { // for every new column a row is added
            char *tmp;
            printf("cnt=%lisize=%li\n", cnt, playfieldsize.y); // added for debugging purpose
            if (tmp = realloc(playfield[cnt], sizeof(char) * playfieldsize.x)) // segfault happens here
                playfield[cnt] = tmp;
            else
                die("Not enough initial memory");
        }
    } else // if storage could not be reallocated
        die("Not enough initial memory");
}

I'm however getting segmentation fault when the array is being accessed with a y value that is constantly being increased by one. This is what the program prints out:

...
cnt=327size=330
cnt=328size=330
cnt=329size=330
cnt=330size=360
cnt=331size=360
Segmentation fault

And I get this segfault when I in the beginning is accessing th开发者_运维百科e array with a few <10 y values and then one of 301:

...
cnt=27size=30
cnt=28size=30
cnt=29size=30
cnt=30size=330
cnt=31size=330
Segmentation fault

So in the first example it initialized rows up until 331 before the error happens, and in the second it fails at 31. I can't figure what is going on, it seems pretty random to me.

This is the entire program if needed: http://pastebin.com/13mRDh8A


Your second realloc (for allocating new rows) should be malloc instead. At that point, playfield[cnt] contains uninitialized data, so trying to realloc it can cause a segfault.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜