Search code examples
carraysdynamicstructrealloc

Dynamic Arrays of Struct


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

struct ver{
    double x;
    double y;
};

struct ver *v=NULL;

int main(){

    v=(struct ver*)realloc(v,1*sizeof(struct ver));

    v[0].x=1.444;
    v[0].y=1.555;

    v[1].x=1.333;
    v[1].y=1.222;

    v[3].x=1.111;
    v[3].y=1.777;

    v[8].x=1.999;
    v[8].y=1.888;

    printf("x:%f y:%f \n", v[0].x, v[0].y);
    printf("x:%f y:%f \n", v[1].x, v[1].y);
    printf("x:%f y:%f \n", v[3].x, v[3].y);
    printf("x:%f y:%f \n", v[8].x, v[8].y);
}

The result is:

 x:1.444000 y:1.555000 
 x:1.333000 y:1.222000 
 x:1.111000 y:1.777000 
 x:1.999000 y:1.888000

Shouldn't i get segmentation fault? It ignores the realloc. I want to make an array of structs which i want to expand 1 array-cell each time.


Solution

  • You only get a segmentation fault if there is no memory behind the address you are accessing. This is meant in a physical sense, a segfault is first signaled by hardware, not by software. Now, physical memory mapping always happens in terms of complete pages. which are 4 kiB on most hardware. The size you requested from realloc() is just 16 bytes.

    Of course, there must be memory behind the address that realloc() returns. Consequently, there must be at least 4080 addresses surrounding your struct that are just as valid in the eyes of the hardware as the 16 addresses belonging to the struct itself. That means that the hardware cannot signal your OS that something might be amiss, and your OS cannot send you a segmentation fault. You might get a segfault if you try to access v[1000], but even that is not certain.

    That does not mean that you are allowed to access these addresses, it just means that you cannot rely on a segfault when you access them. There might be other allocations that you can clobber, or worse, there might be information standing there which malloc uses to determine which memory regions are used and which not. If you access any address outside of the region requested from realloc(), your program has undefined behaviour and anything can happen.