Question

#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.

Was it helpful?

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.

OTHER TIPS

You're calling realloc to allocate a single entry. Accessing anything but v[0] is undefined behavior which may cause a crash, or it may not.

Technically, defining main like you do (without any arguments, not even void) is also undefined behavior as well in C. You either have to declare it with void as argument, or int and char**.

Calling realloc with a NULL pointer is well defined behaviour. So v points to enough memory for exactly one struct ver.

The reason that v[1] is not generating a segmentation fault: Such errors do not have to happen alwyas - you can get lucky... Perhaps realloc also gives you a bit more memory as you only asked for 16 bytes.

Sometimes malloc grabs a big chunk from the OS (so it can use it later) without doing a context switch.

That is expensive.

So you are just lucky

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top