Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why can I write over a piece of memory which has been allocated 0 space?

Tags:

c

Why is it that I allocate a space of size 0 to array but i can still write over that piece of memory?

#include<stdio.h>

int main(int argc, char** argv)
{
   int * array = malloc((sizeof(int)) * 0);
   int i;
   for(i = 0; i < 10; i++)
      array[i] = i;

   for(i = 0; i < 10; i++)
      printf("%d ", array[i]);
}
like image 504
Louis Kuang Avatar asked Feb 09 '23 01:02

Louis Kuang


1 Answers

You code invokes undefined behaviour as you access index out of bounds -

 for(i = 0; i < 10; i++)
 array[i] = i;

You won't get any warning or error about such thing but this is documented in standards that it is UB.

And in that case output could be anything.

And for this line -

int * array = malloc((sizeof(int)) * 0);

C Standard says -

If the size of the space requested is zero, the behavior is implementation-defined: either a null pointer is returned, or the behavior is as if the size were some nonzero value, except that the returned pointer shall not be used to access an object.

Here it's return may or may not be NULL pointer. But it is clear that this pointer should not be used to access any object.

like image 98
ameyCU Avatar answered Feb 11 '23 23:02

ameyCU