Question

I'm trying to understand the how the memory is managed in C. In the sample code below, in the comments I have added my understanding on how the memory is managed.

  1. I would like to know if I'm correct
  2. In the final part of the code, I'm trying to access a part of memory which is already freed. I'm surprised why the compiler did not through any warnings
struct node
{
    int keys[2];
    int *pkeys;
};

int main()
{
    int temp[2] = {10,20}; // creates a temp array in stack
    struct node* node = malloc(sizeof(struct node)); //allocates a block of memory on heap pointed by node
    node->keys[0]=1;node->keys[1]=2;  // assigns values for keys present in heap
    node->pkeys = malloc(2*sizeof(int)); // creates a pointer pkeys in heap
    node->pkeys = temp; // the pointer pkeys in heap points to the temp array in stack
    free(node); // the block of memory on heap pointed by node is freed
    node->keys[0] = 9; //**Why does the compiler ignore that I'm accessing freed memory?**
}
Was it helpful?

Solution 2

The compiler does not check for illegal memory access and your program will cause undefined behaviour or may even crash (segmentation fault). The behaviour is unpredictable and next time you run your program, it may crash.

Few things about your code:

The signature of main should either be int main(void) or
int main(int argc, char *argv[]).

The comment for this statement is wrong.

node->pkeys = malloc(2*sizeof(int)); // creates a pointer pkeys in heap

You created the pointer pkeys when you allocated memory and made node point to it. This statement is dynamically allocating memory for array of 2 ints and making pkeys point to it. So when you do node->pkeys = temp, you lose handle on the dynamically allocated array and will cause memory leak. So before reassigning pkeys, you must free the memory it points to.

free(node->pkeys);

// now reassign node->pkeys

OTHER TIPS

The compiler in C does not do that sort of checking. If gives enough rope to hang yourself.

It is up to you to do the checks. That is also true for bounds checking of arrays.

Also you need to note that malloc/free does not always have to beg/give to the OS. That means it may still be accessible by the process without seg fault.

The space allocated to node is freed but node still points to the same location. So it is still accessible. But if you are unlucky (that is the OS reused the memory for its own purposes) you will get a segmentation fault.

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