metric-space
metric-space

Reputation: 539

possible casting issues with void pointer

I have no clue as to what I am doing wrong with the below code..when compiled normally this is what error I recieve

blob.c: In function ‘main’: blob.c:19:14: warning: dereferencing ‘void *’ pointer [enabled by default] blob.c:19:14: error: request for member ‘x’ in something not a structure or union

#include<stdio.h>
#include<stdlib.h>

typedef struct {

int*x;

}TIM;


main(){
    void*o;

    TIM * a;
    a=(TIM*)malloc(sizeof(TIM));
    a->x=(int*)malloc(sizeof(int));
    *(a->x)=10;
    o=(void*)a; 
    free((TIM*)o->x);

    free((TIM*)o);

}

Could someone please point me in the right direction.Hints are welcome.WHole answers if hint seems too obvious.

Upvotes: 1

Views: 139

Answers (2)

AndersK
AndersK

Reputation: 36082

Your statement

free((TIM*)o->x);

fails because -> has higher precedence than the cast, since o is declared as void* the compiler doesn't know how to handle that.

Upvotes: 1

David Schwartz
David Schwartz

Reputation: 182753

free((TIM*)o->x);

Should be

free(((TIM*)o)->x);

Upvotes: 2

Related Questions