Home > Net >  Why I'm lossing data using realloc()?
Why I'm lossing data using realloc()?

Time:12-21

I'm still a beginner, so I don't know much and I'm sorry if it looks too dumb. I was learning about memory leak and how to use malloc(), calloc(), free() and realloc().

I tried this sample above on visual studio, however when I saw the results after using realloc, I didn't got the same values that was before on that struct.

#include <iostream>
#include <string>


struct sNum
{
    int b = 0;
};

int main()
{
    int n = 10;
    struct sNum* a;
    a =(struct sNum*) malloc(n * sizeof(struct sNum));
    for (int i = 0; i < n; i  )
    {
        a[i].b = i;
        std::cout << std::to_string(a[i].b)   " ";
    }
    std::cout << "\n";
    n  ;
    a = (struct sNum*)realloc(a, n);
    a[n - 1].b = n - 1;
    for (int i = 0; i < n; i  )
    {
        std::cout << std::to_string(a[i].b)   " ";
    }   
    return 0;
}

Running that code on visual studio, it results:

0 1 2 3 4 5 6 7 8 9
0 1 -50331646 -570556931 -572662307 -572662307 -757975909 -2147479587 -572662307 -572662307 10

I was expecting the same sequence, plus 10 at the end. Anyone knows what I'm doing wrong? Thx in advance!

CodePudding user response:

Assuming that sizeof(sNum) is 4 on your platform, the line

a =(struct sNum*) malloc(n * sizeof(struct sNum));

will allocate 40 bytes of memory.

The line

a = (struct sNum*)realloc(a, n);

will shrink the allocated memory to 11 bytes, which is only sufficient to store 2 elements.

Due to this, the line

a[n - 1].b = n - 1;

will invoke undefined behavior, because valid indexes into a are only 0 and 1 (because there is only room for 2 elements), however you are using the index 10.

Therefore, to fix this, you should change the line

a = (struct sNum*)realloc(a, n);

to:

a = (struct sNum*)realloc( a, n * sizeof(sNum) );
  •  Tags:  
  • c
  • Related