Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C: Function returning via void *

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 ?

like image 887
Ande Turner Avatar asked Nov 27 '22 00:11

Ande Turner


2 Answers

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.

like image 199
Amber Avatar answered Dec 22 '22 08:12

Amber


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.

like image 39
William Pursell Avatar answered Dec 22 '22 09:12

William Pursell