Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to properly realloc a calloc?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

#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.

>Solution :

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

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.)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading