【发布时间】:2018-10-02 18:26:20
【问题描述】:
我正在使用以下函数来分配内存:
int qmem_alloc(unsigned int num_bytes, void ** rslt){
void** temp;
if(rslt == NULL)
return -1;
temp = (void **)malloc(num_bytes);
if(temp == NULL)
return -2;
else
rslt = temp;
return 0;
}
以及以下函数来重新分配内存:
int qmem_allocz(unsigned num_bytes, void ** rslt){
void** temp;
void *test = (void *)malloc(10);
if(rslt == NULL)
return -1;
temp = (void **)realloc(rslt, num_bytes);
printf("here");
if(temp == NULL)
return -2;
else
// free(rslt)
return 0;
}
这是我的主要功能:
struct qbuf { int idx; char data[256]; };
void main(){
struct qbuf * p = NULL;
printf("%d\n",qmem_alloc(sizeof(struct qbuf), (void **)&p));
printf("%d\n",qmem_allocz(100*sizeof(struct qbuf), (void **)&p));
}
程序可以获得分配的内存,但在重新分配完成时会崩溃。这是错误:
malloc.c:2868: mremap_chunk: 断言`((size + offset) & (GLRO (dl_pagesize) - 1)) == 0' 失败。
为什么会这样?我该如何解决?
【问题讨论】:
-
在alloc函数返回之前用
*rlst = temp;修复你的代码。rlst = temp;将指针值赋给temp,需要将指针指向的值赋给temp。 -
好奇,谁或什么文字建议铸造,如
(void **),malloc()的结果。? -
void *test = (void *)malloc(10);的原因是什么?它分配内存,然后代码忘记了它。
标签: c memory-management realloc