[英]C Realloc causing segmentation fault
我正在使用以下函数来分配内存:
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'失败。
为什么会这样呢? 我该如何解决?
您在qmem_alloc
分配是错误的。
temp = (void **)malloc(num_bytes); //You are wrongly typecasting, don't typecast the malloc return.
rslt = temp; // This makes rslt points to object where temp is pointing
您只需要执行以下操作。
int qmem_alloc(unsigned int num_bytes, void ** rslt){
if(rslt == NULL)
return -1;
*rslt = malloc(num_bytes);
if(*rslt == NULL && num_bytes > 0)
return -2;
else
return 0;
}
而且您的重新分配是错误的
temp = (void **)realloc(rslt, num_bytes); //You need to pass the object where rslt is pointing.
重新分配的示例代码:
int qmem_allocz(unsigned num_bytes, void ** rslt){
void* temp; // No pointer to pointer is needed
void *test = (void *)malloc(10);
if (test == NULL) return -3;
if(rslt == NULL)
return -1;
temp = realloc(*rslt, num_bytes); //use *rslt to pass the address of object where rslt is pointing.
if(temp == NULL && num_bytes > 0){
return -2;
}
else{
*rslt = temp;
return 0;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.