-1
#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()?

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
  • 2
    Its called UB(undefined behaviour). Anything could happen. – Karthick Jun 28 '18 at 10:11
  • Possible duplicate of [What happens if I try to access memory beyond a malloc()'d region?](https://stackoverflow.com/questions/1655971/what-happens-if-i-try-to-access-memory-beyond-a-mallocd-region) – Stoogy Jun 28 '18 at 13:22
  • @Karthick can it be a reason: malloc allocates a larger block of memory using sbrk() for avoiding future system calls.?? – Vishal Kumar Jun 30 '18 at 19:09

3 Answers3

3

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 i.e 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 e.g

int *a = malloc(sizeof(int));
if( a != NULL) {
   /* allocated successfully & do_something()_with_malloced_memory() */ 
}
else {
    /* error handling.. malloc failed */ 
}
Achal
  • 11,821
  • 2
  • 15
  • 37
2

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.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
0

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.