首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >C真核引起分割断层

C真核引起分割断层
EN

Stack Overflow用户
提问于 2018-10-02 18:26:20
回答 1查看 287关注 0票数 1

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

代码语言:javascript
复制
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;
}

以及以下重新分配内存的功能:

代码语言:javascript
复制
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;
  }

以下是我的主要功能:

代码语言:javascript
复制
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’失败。

为什么会发生这种情况?我怎么才能修好它?

EN

回答 1

Stack Overflow用户

发布于 2018-10-02 18:49:38

您在qmem_alloc中的分配是错误的。

代码语言:javascript
复制
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

你只需要按下面的方式来做。

代码语言:javascript
复制
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.

用于重新分配的示例代码:

代码语言:javascript
复制
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;
    }
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52614251

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档