0

If I use malloc() to allocate memory and do not use free() to de-allocate the the memory. why cannot that memory be accessed by other program by just over writing the previous content

void main()
{
    int *a;            //here a is holding a junk value

    MALLOC(a,1,int);
    *a=100;            //a is holding 100

    MALLOC(a,1,int);
    *a=200;            //a is holding 200 

    /* so memory location where the value 100 is stored is inaccessible
       cannot be reused */
    //why can't we just over write that memory space when used next time
}
Inian
  • 80,270
  • 14
  • 142
  • 161
  • 1
    Never used `malloc` that way (standard syntax is `*malloc(size_t size)`, I think. That way you can't tell the program to allocate memory at the exact same location. – Art May 13 '19 at 09:08
  • If you don't use `free()` you have lost memory allocated by the first malloc and that is inaccessible to you. You're basically leaking memory. Also possible [duplicate](https://stackoverflow.com/questions/19435433/what-happens-if-i-use-malloc-twice-on-the-same-pointer-c) – Pratik Sampat May 13 '19 at 09:09
  • What does `MALLOC` do? – eerorika May 13 '19 at 10:25

1 Answers1

2

You are using a very strange macro, the allocations in standard C would read:

int * const a = malloc(sizeof *a);
if (a != NULL)
{
  *a = 100;
}

then the second allocation is done without calling free(), and overwriting the contents of a; this is very bad since it leaks the memory. That's why I declared it as * const above, to signal that the pointer variable in typical use should not be overwritten since we want to keep its value.

When your program ends, on typical modern systems, all resources used by that process will be reclaimed by the operating system and the memory will be used for something else.

The need to call free() is mostly about allocations done while your program runs, if the allocations happen repeatedly the process will just grow and grow otherwise.

unwind
  • 391,730
  • 64
  • 469
  • 606