itslayer
itslayer

Reputation: 74

Change the address of a variable passed as a void* function parameter

I have a callback function void string_cb(char* data, size_t size, void* str) which uses a prototype void callback_decl (char* data, size_t size, void* ret_val) where the last parameter is a return value. Because my callback needs to allocate a memory for a string with malloc(), I need to change the address of the void* str to allocated memory block. Is it possible to assign a new address to str without changing the callback prototype?

Upvotes: 0

Views: 284

Answers (2)

Serge Ballesta
Serge Ballesta

Reputation: 149155

Yes you can... but not with your string_cb declaration. If you want to be able to return the address of a newly allocated array, you need a char ** as the last parameter:

void slbin_handler_nstring(char* data, size_t data_size, void* ret_ptr) {
    char** ptr = (char **) ret_ptr;
    *ptr = malloc(data_size);
    if (!(*ptr)) return;
    memcpy(*ptr, data, data_size);
}

If should be called that way:

char *ptr;
slbin_handler_nstring(data, data_size, &ptr) ;

Upvotes: 1

Ext3h
Ext3h

Reputation: 6391

With the signature void callback_decl (char* data, size_t size, void* ret_val), the caller is solely responsible for providing allocated memory. It is not possible for the invoked callback to allocate memory internally.

If you think about it for a moment, that's actually to prefer, as the caller knows a lot better where the memory should be allocated (heap or stack), and has full control over the entire life time of the string.

Usually this pattern is combined with a special value for ret_val which indicates provided bufferis too small so that the caller can issue the callback again, but with a larger buffer.

Upvotes: 1

Related Questions