简体   繁体   中英

C Dynamic Memory Allocation to void pointer

I have a function to which I will pass a struct ID and it will return me a string. I will pass a pointer to store the name string and that pointer will be allocated memory by the function called.

int ConvertIDToName(void *id, void *name, size_t *size)
{
    int      status = 0;
    unsigned char *xIDname = "user4.microsoft.com";

    *name = (unsigned char*)malloc(30);
    memcpy(*name, xIDName, *size);

    ...

    return(0);
}

main(int argc, char* argv[])
{
    struct ID_t idObj ={1,5, {0,0,0,0,0,5}};
    unsigned char*      IDName = NULL;
    UINT32          IDNameSize = MAX_CHAR;

    ConvertIDToName(&idObj, &IDName, (size_t *)&IDNameSize);

    return(0);
}

The function ConvertIDToName() fails to store the allocated memory address in the void pointer. I am unable to assign memory in the pointer and it gives me error from 3rd statement of function ConvertIDToName():

warning: dereferencing âvoid *â pointer
    test_code.c:683: error: invalid use of void expression

What am I doing wrong and how to correct it?

The name parameter is of type void * , and you're dereferencing it using *name . What you need to do is use another pointer of type unsigned char ** inside the function or cast name to unsigned char ** before dereferencing it:

/* Use namep instead of name. */
unsigned char **namep = name;

*namep = malloc(30);
memcpy(*namep, xIDName, *size);

...

or:

/* Use casts everywhere. */
*(unsigned char **)name = malloc(30);
memcpy(*(unsigned char **)name, xIDName, *size);

...

Edit

As suggested by @WhozCraig, you may also make your function require the name to be void ** instead of void * . This will avoid the need for type casting or another variable. It is a great suggestion since malloc returns a void * and memcpy requires a void * parameter. Dereferencing a void ** will yield a void * to work with.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM