Click here to Skip to main content
15,067,335 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
C++
int *p=(int *)malloc(0*sizeof(int));


What is the meaning of this?
Is this same as creating a pointer pointing to NULL

What I have tried:

I tried searching in google ......
Posted
Updated 27-Jul-21 22:08pm
Comments
jeron1 28-Jul-21 10:14am
   
Just curious, where did you happen upon this line of code?
_-_-_-me 28-Jul-21 10:54am
   
:-)
I did not use it anywhere . I just got that doubt that what happens in this case.


1 solution

Well ... no, not quite.
It's a valid pointer you get, but it's zero bytes long and cannot be dereferenced:
If the size of the space requested is zero, the behavior is implementation defined: either a null pointer is returned, or the behavior is as if the size were some nonzero value, except that the returned pointer shall not be used to access an object.

It's a bit useless, as free is defined to accept a NULL value:
The free() function shall cause the space pointed to by ptr to be deallocated; that is, made available for further allocation. If ptr is a null pointer, no action shall occur. Otherwise, if the argument does not match a pointer earlier returned by a function in POSIX.1-2017 that allocates memory as if by malloc(), or if the space has been deallocated by a call to free() or realloc(), the behavior is undefined.

It's a lot clearer to just use
C
int *p = NULL;
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900