[Solved] What is wrong with this void pointer to struct cast? [closed]


Answer was provided before language tag was changed from C to C++.

struct MyStructData
{
    VOID* pPtr;
    UINT32 flags;
}

There are no types VOID or UINT32 in C unless you include some headers providing them. Maybe some Windows stuff?

Also a ; is missing after that struct declaration. (Thanks to wildplasser)

VOID main()

Valid signatures for main are int main(void) or int main (int argc, char *argv[]) or compatible.

{
    MyStructData* pMyStructData = InitFunction();

There is no type MyStructData. Use struct MyStructData or add a typedef.

You do not provide a prototype for InitFunction().

    // work done here
    DeInitFunction(pMyStructData);
}

Same here: No prototype for DeInitFunction

MyStructData* InitFunction()
{
    MyStructData* pMyStructData = malloc(sizeof(MyStructData));

Again: Use struct MyStructData.

Use of malloc without prototype. Include proper headers.


    pMyStructData->pPtr         = malloc(1024);

Basically valid (except for missing prototype), but you should check if pMyStructData is NULL before dereferencing it.


    return pMyStructData;
}

VOID DeInitFunction(MyStructData* pMyStructData)
{
    free(pMyStructData);
}

As Johnny Mopp mentioned, pMyStructData->pPtr is not freed causing a memory leak.

Again: No type VOID and MyStructData.

Again: Use of function (free) without prototype.

Now regarding your findings:

I see the void pointer is declared, then in InitFunction, pMyStructData has
malloc with size of the struct MyStructData.

Apart from the issues I mentioned abov, that is fine. That is how allocating memory for structs is don.

Next the pPtr member is accessed and malloc-ed a big chunk (1024)… this
is where I see an issue. Since the pPtr member was declared as void,
pMyStructData is too small to allocate 1024 bytes?

That is no issue. The member ptr points to some memory provided by malloc There is no relation to the struct where the pointer itself resides. It does not need to fit into the struct.
You only should check for NULL before this.

7

solved What is wrong with this void pointer to struct cast? [closed]