Home > database >  How to properly realloc a calloc?
How to properly realloc a calloc?

Time:03-25

can someone tell me how to use realloc to properly extend calloc?

my expectation: all 20slots to have value of 0.

Outcome: only calloc slots have value of 0, the one I allocate with realloc have random number. output picture

#include <stdio.h>
#include <stdlib.h>
int main(){
    int *ptr;
    int i;
    int n =10;
    ptr = (int*)calloc(n, sizeof(int));    //first time allocate with calloc
    ptr = (int*)realloc(ptr,2*n*sizeof(int));  //extend with realloc
    
    for(i=0;i<2*n;i  ){
        printf("ptr[%d]: %d \n", i, ptr[i]);
    }
    return 0;
}

NOTE: before anyone ask why don't I just use calloc(20,sizeof(int));. This is not the real program that I am writing, this is just a short demo so people can see my problem easier. I actually intent to extend calloc much later in the program.

My attempt to find the answer before creating this question. I had google this:

  • How to realloc properly?
  • How to extend Calloc?
  • How to use realloc with calloc?
  • calloc() and realloc() compiling issue
  • several similar to the above.

But I seem to can't find the real answer to this(I might missed it, I'm really sorry). Most of the answer that I got is that they use realloc to extend calloc just like I did, but that is exactly my problem. sorry for bad English.

CodePudding user response:

The C standard does not provide any routine that performs a reallocation and zeros the additional memory. To achieve this, you can implement it yourself by using realloc to reallocate memory and clearing with memset:

int *newptr = realloc(ptr, 2 * n * sizeof *newptr);
if (!newptr)
{
    fprintf(stderr, "Error, unable to allocate memory.\n");
    exit(EXIT_FAILURE);
}
ptr = newptr;
memset(ptr   n, 0, n * sizeof *ptr);
n *= 2;

You could of course wrap this into a routine, say one called crealloc, and use that. (Unlike the library functions for memory management, it would have to be passed the size of the prior allocation, since code you write does not ordinarily have access to the memory management data structures that provide that size.)

  • Related