【问题标题】:C Realloc causing segmentation faultC Realloc 导致分段错误
【发布时间】: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


【解决方案1】:

你在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;
    }
}

【讨论】:

    猜你喜欢
    • 2014-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-25
    • 1970-01-01
    相关资源
    最近更新 更多