Why can I write over a piece of memory that has been allocated 0 spaces?

Why am I allocating space of size 0 to an array, but can I still write this 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]);
}
+4
source share
3 answers

You cause undefined behavior when accessing the index outside the limits -

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

You will not receive any warnings or errors about this, but it is confirmed in the standards that it is UB .

And in this case, the conclusion can be any.

And for this line -

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

C Standard says -

, : , , , .

NULL pointer. , .

+6

malloc 0 NULL, , free. , , , , , (= > undefined).

+2

C - . , :

  • / / .
  • (void* ).
  • .
  • Unmanaged.
  • Etc...

As these actions are risky and can lead to Memory Leak, Memory Corruptionand other undesirable effects, you should avoid such actions when they are not needed, and maintain a clean and conditional code (make it 10a constant and avoid working with unallocated memory ).

0
source

Source: https://habr.com/ru/post/1607280/


All Articles