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.
Also, it's always a good practice to check the success of malloc()
before using the returned pointer to avoid the possible UB by dereferencing NULL in case of malloc()
failure.