简体   繁体   中英

Strange memory allocation in case of pointers using malloc

#include <stdio.h>
#include <stdlib.h>

int main()
{
int *a = (int *)malloc(sizeof(int));
//    int a[1];
int i;
for(i = 0; i < 876; ++i)
    a[i] = i;
printf("%d",a[799]);
}

Why is this code working, even if, I am allocating only 1 int's space using malloc() ?

Why is this code working? Even if, I am allocating only 1 int's space using malloc ? In such case answer in undefined behavior.

Allocating block of 4 bytes like

  int *a = (int *)malloc(sizeof(int)); /* No need to cast the malloc result  */

and accessing beyond that like

a[i] = i; /* upto i<1 behavior is guaranteed as only 4byte allocated, not after */

results in undefined behavior ie anything can happen and you shouldn't depend on it doing the same thing twice.

Side note, type casting the result of malloc() is not required as malloc() return type void* & its automatically promoted safely into required type. Read Do I cast the result of malloc? And always check the return value malloc() . for eg

int *a = malloc(sizeof(int));
if( a != NULL) {
   /* allocated successfully & do_something()_with_malloced_memory() */ 
}
else {
    /* error handling.. malloc failed */ 
}

It seems to be working. There is absolutely zero guarantee it will work the same way after a recompile, or in a different environment.

Basically, here you're trying to access memory address, which is not allocated to your program (using any index other than 0 ). So, from your program point of view, the memory address is invalid . Accessing invalid memory location invokes undefined behaviour .

As others have explained, the behavior while accessing a memory region beyond what is allocated, is undefined. Run the same program on a system which is running memory intensive applications. You might see a SIGSEGV. Run your code through coverity static analysis and you will see it catching the buffer overrun.

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