我使用以下函数分配内存:
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:断言‘((大小+偏移)& (GLRO (dl_pagesize) - 1)) == 0’失败。
为什么会发生这种情况?我怎么才能修好它?
发布于 2018-10-02 18:49:38
您在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;
}
}https://stackoverflow.com/questions/52614251
复制相似问题