Rajith Gun Hewage
Rajith Gun Hewage

Reputation: 532

realloc does not provide all the values that were there in the old array

I tried to use realloc in a code I am working on and once I do the realloc not all the values that were in the original array are present in the newly allocated array. The code is as follows.

#include <stdio.h>
#include <stdlib.h>

#define CONST1 20
#define CONST2 2

int main() {

    double *a = (double *) malloc(sizeof(double) * CONST1);

    int i;

    for (i = 0; i < CONST1; i++) {
        a[i] = i * i;
    }

    for (i = 0; i < CONST1; i++) {
        printf("%.0lf ", a[i]);
    }
    printf("\n");

    double *b = (double *) realloc(a, CONST1 + CONST2);

    a[CONST1] = 11;
    a[CONST1+1] = 12;

    for (i = 0; i < CONST1+CONST2; i++) {
        printf("%.0lf ", b[i]);
    }
    printf("\n");
    return 0;
}

The output I got for running this code is;

0 1 4 9 16 25 36 49 64 81 100 121 144 169 196 225 256 289 324 361 
0 1 4 0 16 25 36 49 64 81 100 121 144 169 196 225 256 289 324 361 11 12

Can anyone point out to me the reason for the second 0 in the second row? It works fine when the CONST1 value is set to 4. After 4 it shows this behaviour where either one or two values are set to 0.

Upvotes: 0

Views: 33

Answers (1)

MikeCAT
MikeCAT

Reputation: 75062

Assuming double is 8-byte long, I guess b happened to be the same as a and some 0x00 bytes are written to the buffer after the newly allocated buffer to manage something.

You made two mistakes:

  • The a passed to realloc() is deallocated, according to N1256 7.20.3.4 The realloc function, so you must not use it. You assigned the new pointer to b, so use b.
  • The size to be passed to realloc() should be sizeof(double) * (CONST1 + CONST2), not CONST1 + CONST2.

Also whatever is allocated should be freed, so you should add free(b); before return 0;.

Upvotes: 3

Related Questions