Reputation: 345
Correct me if I am wrong but does
malloc(1) // Mallocing 1 which is a int
equal
malloc( sizeof(1) )
Upvotes: 1
Views: 2856
Reputation: 213960
Integer constants such as 1
have their own type just as variables do. In this case int
.
Meaning that sizeof(1)
is equivalent to sizeof(int)
.
So malloc(1)
means "allocate 1 bytes", while malloc(sizeof(1))
means allocate as many bytes as the size of an int.
Upvotes: 1
Reputation: 409196
The size of an integer constant depends on the value of the constant and on a possible suffix. Integer constants are at least of the type int
if it fits in an int
, if the value of the constant is larger and don't fit in an int
then long
or long long
are used. The constant 1
is small enough to fit in an int
so sizeof(1) == sizeof(int)
is true.
However, malloc( sizeof(1) ) == malloc( sizeof(int) )
will not be true, since you allocate two different memory areas and each call will return different pointers. The sizes of those memory areas will be the same, but not the pointers returned by malloc
. The exception being if both malloc
calls fail and return NULL
.
I know that you probably don't mean the comparison of the malloc
calls literally, but in programming such things are important to spell out. Semantics is very important.
As for the question in your title, malloc(1)
returns a pointer to one single byte.
Also be careful with assuming sizes, because sizeof(int)
may actually not be four bytes. On small embedded platforms (or very old systems) it could be two bytes. And on future systems it might be eight or even more.
You might want to read e.g. this malloc
reference where it says that the argument is the number of bytes to allocate.
Upvotes: 3
Reputation: 948
void* malloc(size_t)
returns a pointer, and the memory after the pointer has been allocated with size equal to the argument fed into malloc
. In your case, malloc(1)
simply allocates a single byte, while malloc(sizeof(int))
allocates 2 or 4 bytes.
malloc(sizeof(1))
and malloc(sizeof(int))
are equivalent statements but the latter is more apparent. Hence malloc(1)
is not equivalent to malloc(sizeof(1))
as sizeof(1) == 4
. (Or sometimes 2, 8)
Upvotes: 6