开发者

callin' c from lua crashs while reallocating

开发者 https://www.devze.com 2022-12-31 18:33 出处:网络
i got a crazy error within that for-loop matr=realloc(matr, newmax*sizeof(matr*)); for (i=0; i<newmax; i++){

i got a crazy error within that for-loop

matr=realloc(matr, newmax*sizeof(matr*));

for (i=0; i<newmax; i++){
    matr[i]=realloc(matr[i], newmax*sizeof(int));
}

matr 开发者_如何转开发is a multi-dimension array: int **matr. i need to resize column and row. first line resizes column and the for-loop resizes every row. it worked fine in c. now im working on a library for lua and it crashs here. compilin' works fine as well. but calling from lua crashs with

lua: malloc.c:3552: mremap_chunk: Assertion `((size + offset) & (mp_.pagesize-1)) == 0' failed.

i have no damn idea since it's working fine using it in c.


After calling realloc, the contents of the newly allocated portion are indeterminate. This means that then calling realloc on the new rows may fail because it tries to reallocate an invalid pointer.

You can use realloc on the old rows and malloc on the new rows to fix this. Or you can zero the new part after the first realloc, and then your loop will work as is:

matr=realloc(matr, newmax*sizeof(matr*));
for (i=oldmax; i<newmax; i++)
    matr[i] = NULL;

for (i=0; i<newmax; i++){
    matr[i]=realloc(matr[i], newmax*sizeof(int));
}
0

精彩评论

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

关注公众号