C重新分配导致分段错误

时间:2018-10-02 18:26:20

标签: c memory-management realloc

我正在使用以下函数来分配内存:

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'失败。

为什么会这样?我该如何解决?

1 个答案:

答案 0 :(得分:2)

您在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;
    }
}
相关问题