zoNNN zoNNN - 4 months ago 21
C Question

How to limit the size allocated memory?

While studying pointers I found that if I allocate memory for a 2 digit int I can give that int a higher value. Can someone explain me why it works like that and how to work around it?

Here is the code:

int *p;

p = (int *) malloc(2*sizeof(int));
p = 123456;


First of all, Please see this discussion on why not to cast the return value of malloc() and family in C..

That said, here, you're just overwriting the pointer returned by malloc(). Don't do that. It will cause memory leak. Also, if you try to dereference this pointer later, you may face undefined behavior, as there is no guarantee that this pointer points to a valid memory location. Accessing invalid memory leads to UB.

Finally, to address

I allocate memory for a 2 digit int [...]

let me tell you, you are allocating memory to hold two integers, not a two digit integer. Also, to store the integer values into the memory area pointed by the pointer, you need to dereference the pointer, like *p and store (assign) the value there, like *p=12345;.

malloc() allocates memory of the size of bytes passed as it's argument. Check the sizeof(int) (and 2*sizeof(int), if you want) to make it more clear.

Regarding this, quoting C11, chapter

void *malloc(size_t size);

The malloc function allocates space for an object whose size is specified by size [...]

So, here, malloc() returns a pointer with the size of two integers (i.e., capable of holding two integer values), not two digits or bytes.