簡體   English   中英

C重新分配導致分段錯誤

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM