简体   繁体   中英

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

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]);
}

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.

malloc with an argument of 0 returns either NULL or a unique pointer that can be passed to free . If it does return a non-null value and that pointer points to memory that's within a page that's valid for your program and writable, the operating system won't zap you if you try to write to it, but you might end up rewriting some parts of your program's data (=> undefined behavior).

C is an unsafe language . as an unsafe language it allows you to do risky actions as the following:

  • Writing/Reading to/from unallocated memory.
  • Implicity casting types ( void* to other types and vica versa).
  • No bound checks.
  • Memory is Unmanaged .
  • Etc...

Since those actions are risky and might lead to Memory Leak , Memory Corruption and other unwanted results, you should avoid doing such things when they are not neccesary and keep clean and conventioned code (make this 10 a constant and avoid working on unallocated memory ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM