int p = (int *)malloc(sizeof(int));
and,
int p = (int)malloc(sizeof(int));
could anybody explain me what occurs internally and what the difference between using (int*) and (int)?
Thanks.
Both of your examples are "bad".
The first one is incorrect, as it tries to assign a pointer to an integer, and thus should at the very least give a warning, more likely an error. And if the machine is 64-bit and you are compiling it as 64-bit code, the pointer may not fit in the integer [same applies to a 16-bit int on a 32-bit machine, but that's not very common these days].
The second example will most likely compile, but it's still assigning an integer with the value of a pointer, which is pretty much pointless (and it may not fit, as pointers are bigger than int).
In "C", you should not use casts to assign the value returned by malloc - it is wrong, and can lead to problems.
In "C++", you should not use malloc, use new instead.
Since this is tagged C++ I'll take the C++ angle to the answer:
int p = (int *)malloc(sizeof(int));
int p = (int)malloc(sizeof(int));
Both of these are wrong, malloc returns a pointer to some memory. I think what you actually wanted was to allocate an int on the heap, thus your return value is int*.
Depending on 32 or 64bit arch this code will break because you are going to assign 64bits of data to 32bits of storage.
The correct way in C is:
int* p = malloc(sizeof(int));
Which is saying, allocate enough space for the type int, and store a pointer to this allocated space. No cast is required in C.
In C++ it would look like this if you used malloc:
int* p = static_cast<int*>(malloc(sizeof(int)));
Now the cast IS required, however you can avoid this by using operator new:
int* p = new int; // much cleaner!
Note that operator new will throw std::bad_alloc on failure rather than returning nullptr/0/NULL.
If you don't want it to throw but want the cleaner syntax you can use:
int* p = new (std::nothrow) int;
Or even better still, either don't allocate on the heap unless really needed, or use a smart pointer so you don't have to worry about calling operator delete or free():
std::unique_ptr<int> p(new int); // when p leaves scope, the memory is deleted
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With