-4

So I am learning dynamic memory allocation nowadays and stuck in a problem(if it is).

int *p;
p=(int*)calloc(5,sizeof(int));

According to my intution p should point to memory location of 5*4 = 20byte and these 20bytes only belong to p. for *(p+0), (p+1)....(p+4) everything is fine. but when i do *(p+5) or *(p+12)=100; This should give me an error as i have exceeded the memory block allocated to *p.

The confusion is : Why we need to even allocate memory when we can just do like :

int *p
int s[]={1,2,3}
p=&s[0]
//and then make an array of length > s
*(p+4)=....something

In every article i am seeing they are allocating memory before assigning . what's the need. I hope u understand my confusion.

rohit kumar
  • 43
  • 1
  • 4
  • "This should give me an error". That isn't a correct assumption. Read the duplicate candidate link. Basically accessing invalid memory is undefined behaviour. It doesn't have to "break" immediately or in any specific way. – kaylum Jan 11 '20 at 03:59

1 Answers1

1

According to my intution p should point to memory location of 5*4 = 20byte

Assuming the size of int is 4 on that system, then the allocation is 20 bytes yes.

and these 20bytes only belong to p

Indeed. p is the only pointer to the allocation, so it is the only pointer that can be used to free it, so it is said to be the "owner" of the memory.

but when i do *(p+5) or *(p+12)=100; This should give me an error

No. The behaviour of accessing memory out of bounds is undefined. There is no guarantee of an error.

Why we need to even allocate memory when we can just do like :

Because we don't want to have undefined behaviour in our programs. Having undefined behaviour is typically a serious bug. We don't want our program to crash. We don't our programs to delete all our data. We don't want our programs to leak our customer data to hackers. Instead we prefer our programs to have defined behaviour so that we can control that behaviour.

eerorika
  • 232,697
  • 12
  • 197
  • 326