C: Function returning via void *

11,985

Solution 1

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.

Solution 2

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.

Solution 3

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.

Solution 4

Yes. void* meaning pointer to something, but of no particular type.

Solution 5

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*

Share:
11,985
Erwan
Author by

Erwan

Updated on June 11, 2022

Comments

  • Erwan
    Erwan almost 2 years

    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 ?