Click here to Skip to main content
15,867,704 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
malloc function return the address on the first byte of the memory area but malloc function looks like:

void *malloc(size_t size)

void pointer must not return any result, so how does it work?

What I have tried:

-----------------------------------------------------
Posted
Updated 3-Jan-21 6:22am
Comments
CPallini 3-Jan-21 11:41am    
Don't use malloc in C++.
Don't even use new in C++.

This is a C function although you can choose to use it C++ too. The result must be cast to the desired result type, e. g.:
C++
char * my_10_characters = (char*)malloc(10);


P.S.: I've mentioned that this is a C function, because in C++ you should use the new operator instead, which works without casting.
 
Share this answer
 
v2
Comments
temchik_ggg 3-Jan-21 11:25am    
Yep I know that in C++ the new operator is being used more often than malloc function, but I found prototype malloc function
(void *malloc(size_t size))
and I can't realise why malloc is pointer on void type?
Stefan_Lang 3-Jan-21 11:32am    
Mostly because C uses a function for this, and you can't define functions that only differ by return type. Moreover the C langauage can't possibly provide one function for each type, because the number of possible types is infinite.

The C++ new operator can work around that problem because it takes the result type as an argument. That makes each 'new' a different function that can have a different return type.
CPallini 3-Jan-21 11:40am    
5.
To add to what Stefan said. The returned pointer is declared void because malloc has no way of knowing what you plan to store i the memory space. The caller uses a cast to let the compiler know what types are going to be used by the rest of the code. So if you want a block of 20 integers you would code something like:
C++
int* pInts = (int*)malloc(20 * sizeof(int));

The malloc code just gets the required amount of space and returns its pointer to the caller. The cast to int* tells the compiler that you will be using it to access int types.
 
Share this answer
 
v2
Comments
CPallini 3-Jan-21 11:46am    
5.Add a ')', though.
Richard MacCutchan 3-Jan-21 11:48am    
Thank you, on both counts.
Stefan_Lang 3-Jan-21 12:24pm    
Indeed - I thought I had mentioned that malloc doesn't know the required type, but apparently I forgot. My 5!
Richard MacCutchan 3-Jan-21 12:29pm    
Thank you.
In addition to Stefan's excellent answer, have a look, for instance, at void pointer in C / C++ - GeeksforGeeks[^].
 
Share this answer
 
v2
Quote:
I can't realise why malloc is pointer on void type?

Simple: a pointer to void can be cast to any type, and since C had no OOPs features such as overloading, polymorphism, etc., a single, universal pointer was needed. Think about it: if you create a C-style struct and you want to allocate instances on the heap - which you probably do want to do - then without a single universal pointer type how are you going to return it? Yes, you could use an int* but then you could dereference it, and that's a bad idea from a reliability point of view - because if you allocate an array of your struct any pointer arithmetic will be in int units not struct units - so they would no reach the "next" struct.

Returning a void* ghets round both problems - you have a universal pointer that can't be dereferenced, so it has to be cast to the right "sort of data" before you can use it.
 
Share this answer
 
Comments
Stefan_Lang 3-Jan-21 12:31pm    
Indeed, I never thought of dereferencing a void*. When I think about it it's obvious you can't, but it's well worth mentioning in this context!
You're thinking the void means "no return value". Fair enough considering you're looking at this:
C
void *malloc(size_t size)

That's not what you're really looking at. What you should be seeing is:
C
void* malloc(size_t size)

Now it's a lot more obvious you're getting back a "void pointer", which just means a pointer to an unknown type. These can be cast to whatever type you need it to be.
 
Share this answer
 
v2
Comments
Stefan_Lang 3-Jan-21 12:26pm    
A fair point. Just clarifying that there is a subtle but imortant difference between a void return value and a void* might have been all that's needed.
You are right that a function return a void is not returning anything. However, this function returns a type of (void *). I wrapped it in parenthesis so you can see it as a singular type. In the Windows SDK they have wrapped it in a type definition :
typedef void * PVOID;
This lets you refer to it as a PVOID. The difference here is a void * is an un-typed pointer. It could point to any possible kind of data. As the other solutions show, you have to cast the result of malloc (and calloc and realloc) to the type of the data you are using. Here's a handy little macro that will do the casting for you :
C++
#define AllocateMemory( count, type )  (type*)calloc( count, sizeof( type ) )
This uses calloc which is just like malloc except it zeros the memory for you automatically which I find very useful. If you want a bunch of integers you can call it like this :
C++
int * intArray = AllocateMemory( 137, int );
and that will allocate memory for 137 integers and set them all to zero.

In C++ it is best to use an automatic memory class like a unique_ptr. [^].
 
Share this answer
 

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