1

I am using following function to allocate memory:

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

And following function to reallocate memory:

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

Here is my main function:

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));
}

The program can get memory allocated but it crashes when reallocation is done. Here is the error:

malloc.c:2868: mremap_chunk: Assertion `((size + offset) & (GLRO (dl_pagesize) - 1)) == 0' failed.

Why is this happening? How can i fix it?

3
  • 5
    Fix your code with *rlst = temp; before return in the alloc function. rlst = temp; assigns the pointer value to temp, you need to assign the value to which the pointer points to temp. Commented Oct 2, 2018 at 18:27
  • Curiosus, who or what text suggested casting, like (void **), the result of malloc().? Commented Oct 2, 2018 at 19:08
  • What is the reason for void *test = (void *)malloc(10);? It allocates memory and then code forgets about it. Commented Oct 2, 2018 at 21:15

1 Answer 1

2

Your allocation in qmem_alloc is wrong.

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

You simply need to do as below.

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

And your reallocation is wrong

temp = (void **)realloc(rslt, num_bytes); //You need to pass the object where rslt is pointing.

Sample code for reallocation:

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;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.