-1

my question is: if I allocate memory using malloc and supposing the memory space end, when I use a subsequent malloc function can the latter overwrite the previous space ? Should an error message occurs ? How can I to avoid this issue ?

Consider this sample of c code:

double *t;    
    t = (double *)malloc(dim*sizeof(double));
    if(t == NULL)
    {
        puts("MALLOC ERROR"); 
        return 1;
    } 

double *t2;    
    t2 = (double *)malloc(dim*sizeof(double));
    if(t2 == NULL)
    {
        puts("MALLOC ERROR"); 
        return 1;
    }

how can i be sure that t2 does not overwrite the memory space of t ?

Andrea
  • 89
  • 9
  • The [ill-advised casting of `malloc`](https://stackoverflow.com/a/605858/1322972) notwithstanding, you can be sure because the language standard says so. The pointer returned by `malloc`, if non-null, is the key to that memory castle you requested, and *only* that memory. Stay within the bounds of your request and only that memory will be accessed. Of course, as soon as you `free` that memory it's back in the pool for someone else to (potentially) acquire with a subsequent allocation request. – WhozCraig Dec 31 '20 at 10:40
  • Where in the sample code you show does “the memory space end”? At the point where the second `malloc` occurs, `t` is still available and contains the value returned by the first `malloc`. – Eric Postpischil Dec 31 '20 at 11:54
  • Re “how can i be sure that t2 does not overwrite the memory space of t1 ?”: There is no `t1` in your sample code. – Eric Postpischil Dec 31 '20 at 11:55
  • My question was: suppose with t the memory ends, should t2 overwrite the space dedicated to t or other variables? Now I know the answer, that is no. – Andrea Dec 31 '20 at 12:26

2 Answers2

0

If t is not NULL that means memory was allocated to it.

So unless you free that memory via free(t), it won't be allocated to t2.

Karthik Nayak
  • 731
  • 3
  • 14
0

Can A Subsequent Malloc Function Overwrite A Previous One?

No.

if I allocate memory using malloc and supposing the memory space end, when I use a subsequent malloc function can the latter overwrite the previous space ?

No.

Should an error message occurs ?

No. No "message" is printed by malloc. malloc only returns NULL in case of error. You print the message puts("MALLOC ERROR"); in the code you posted.

how can i be sure that t2 does not overwrite the memory space of t1 ?

You can make sure that your toolchain follows the standard. Working with a certificated compiled would be a way to "make sure" that is works correctly. I think any valid malloc implementation shouldn't allow any "overwriting" to happen.

KamilCuk
  • 120,984
  • 8
  • 59
  • 111