C: Function returning via void *
-
10-07-2019 - |
Question
Coming from Java I'm confused by the use of Void allowing a return value in the following:
void *emalloc(size_t s) {
void *result = malloc(s);
if (NULL == result) {
fprintf(stderr, "MEMORY ALLOCATION FAILURE\n");
exit( EXIT_FAILURE );
}
return result;
}
Is this returning a pointer to a chuck of allocated of memory ?
Solution
Yes, it is. A void* pointer is basically a generic pointer to a memory address, which could then typically be typecast to whatever type was actually desired.
OTHER TIPS
Your question indicates that you are misreading the function's return type. There is a big difference between:
void foo( void ) {}
and
void *bar( void ) {}
foo() takes no arguments and does not return a value, while bar() takes no arguments and returns a generic pointer. In C, the keyword void is used to indicate a generic pointer, and an object of type void * can be converted to any other object pointer type without loss of information.
Yes, this function is returning a pointer to allocated memory of a specified size. It's different in malloc in the sense that it's guaranteed to return a pointer. On failure it will exit the application.
Yes. void*
meaning pointer to something, but of no particular type.
void means essentially no type, so if we have void *p; p is a pointer to something, but we haven't said what.
void without a pointer is nothing hence void foo(void) being a function that takes no arguments and returns nothing.
And yes malloc returns a pointer to some chunk of memory, malloc doesn't know or care what type that memory has, so it's return type is void*
In Java there is no pointer arithmetic. It think this is what you are asking about. For example, imagine that malloc
returns a pointer of type int
int* malloc(size_t size)
{
//
}
You would possibly receive the pointer, which is basically a pointer to an array
. Then you would index it like regular arrays.
int* arr = malloc(10 * sizeof(int)); // 10 contiguous int(s).
The problem is that C
doesn't have functions overloading. So, we have to find a way to write a generic malloc
. Otherwise, you would end up with a different malloc
for every type. The solution, is to send the required number of bytes that you need. Then, you can index it however you like. This gives a greater flexibility and one for all solution.
int* i = (int*)malloc(10 * sizeof(int)); // 40 bytes if int = 4 bytes
char* c = (char*)malloc(10 * sizeof(char)); // 10 bytes if char = 1 byte
int thirdElement = i[3]; // third element. 12 bytes away from (*i)
char secondElement = c[2]; // second element. 2 bytes away from (*c)
So, the whole idea is that it doesn't matter how we index the memory we got from malloc
. All what we have to do is to specify the type of the newly created array to index it properly. void*
means that this is a pointer to place in memory that we haven't specified how to index.