Shahar Galukman
Shahar Galukman

Reputation: 902

realloc return null

I have a simple program, for learning purposes, yet I keep on getting null returned when I realloc from allocated array.

#include <stdio.h>

#include <stdlib.h>


void main() 
{
    char *ptr, *retval;

    ptr = (char *)calloc(10, sizeof(char));

    if (ptr == NULL)
        printf("calloc failed\n");
    else
        printf("calloc successful\n");

    retval = (char *)realloc(ptr, 5);

    if (retval == NULL)
        printf("realloc failed\n");    
    else
        printf("realloc successful\n");

    free(ptr);
    free(retval);

}

I'm not able to realloc, retval = (char *)realloc(ptr, 5); what am I doing wrong?

Upvotes: 1

Views: 1143

Answers (2)

jcoder
jcoder

Reputation: 30055

This works for me when I compile it. You have one bug though which is that you are calling "free(ptr)" when the memory pointed to by ptr is no longer valid as you realloced it. It maybe the same as retval though too in which case you are freeing it twice.

Upvotes: 1

David Schwartz
David Schwartz

Reputation: 182855

It works as expected for me:

calloc successful
realloc successful
*** glibc detected *** double free or corruption

The code looks fine, assuming the double free was intentional. Don't call free(ptr) since you've already released it by reallocating it.

Upvotes: 3

Related Questions