Enzio
Enzio

Reputation: 889

realloc function doesn't preserve existing memory for me

I created a memory block with 4 units using calloc function where each unit is 1 byte.

Then I assigned it to a char pointer and filled the units with char values.

Then using realloc function I enlarged each unit to 4 bytes (size of an integer) Then I assigned it to a int pointer and filled integers in 3 of the units.

Theoretically I expected that the for the 4th unit of the memory block, value I gave before realloc will be preserved. But it is not. When I compile, each time I get a random value for that.

 int main() {


    //create a memory block of 4 units (each 1 bytes : char size)
    char *p = (char*)calloc(4,sizeof(char));

    //fill the memory units with chars
    p[0] = 'A';
    p[1] = 'B';
    p[2] = 'C';
    p[3] = 'D';

    //print 
    for(int i = 0; i< 4 ; i++){
        printf("%c \n",p[i]);
    }

    //print integer value of third index
    printf("Third index integer value : %d\n",p[3]);

    printf("\n"); //space



    //change the memory block so that each unit = 4 byte (size of integers)
    int  *B = (int*)realloc(p, sizeof(int));
    p = NULL;


    //fill 3 of the 4 memory units with integers
    B[0] = 20;
    B[1] = 25;
    B[2] = 30;


    //print integers
    printf("%d \n", B[0]);
    printf("%d \n", B[1]);
    printf("%d \n", B[2]);
    printf("Third index integer value : %d \n", B[3]);

    printf("Third index char value : %c \n", B[3]);

    return 0;
}

Outcome

attempt 1

B 
C 
D 
Third index integer value : 68

20 
25 
30 
Third index integer value : 53491 
Third index char value : ó 

attempt 2

A 
B 
C 
D 
Third index integer value : 68

20 
25 
30 
Third index integer value : 42319 
Third index char value : O 

Upvotes: 0

Views: 272

Answers (1)

Read suitable documentation of realloc: its size parameter is the new size of memory to allocate. You're asking it to allocate sizeof(int) bytes, which is likely 4 (the same as the size of your previous allocation).

From the C-style allocation functions, calloc is the only one which works in terms of cells & cell size. Everything else (malloc, realloc, even the C++ allocation functions ::operator new and ::operator new[]) works in raw memory size only. So change you call to:

int  *B = (int*)realloc(p, 4 * sizeof(int));

Upvotes: 2

Related Questions