开发者

Problem when typecasting a void * pointer used inside a structure to an int * pointer!

My code is as follows,

#include<stdio.h>
struct data
{
    int a ;
    void *b;
};

int main()
{
    struct data *d;
    int *ptr;

    int key=10000;
    d->b=&key;

开发者_开发知识库    ptr=(int *)d->b;
    printf("%d\n",*ptr);
}

And i get a segmentation fault!! Any idea why?? Thanks in advance for any help


struct data *d merely declares a pointer. You have not allocated this struct anywhere. You need to either malloc it or declare it just as struct data d on the stack or globally.

The former can be done like this:

d = malloc(sizeof(struct data));

If you choose the latter, accessing b has to be written as d.b.


You are not allocating any memory for d. It likely points to an invalid memory area and so - segmentation fault.

You can solve this like so:

struct data *d = malloc(sizeof(*d));


You are getting segmentation fault at the line d->b=&key; Note that you have not allocated any memory location to the structure variable d. So d contains some garbage value, and d->b it trying to use that garbage address to dereference the pointer and get the component b. Here is where you get the segfault. Either statically allocate the struct variable, or use malloc to dynamically allocate it.

int main()
{
    struct data *d;
    int *ptr;

    /* Here you are allocating memory to the
     * pointer variable, which will be used to
     * point to the structure type data
     */
    d = malloc (sizeof (struct data)); 
    int key=10000;

    /* Now you can dereference the pointer 
     * and get any of the components of the
     * structure, because 'd' contains a valid
     * address.
     */ 
    d->b=&key;

    ptr=(int *)d->b;
    printf("%d\n",*ptr);

    /* Good practice to free the memory location
     * you have allocated. Not freeing will lead to
     * memory leak in larger applications. After you 
     * free the memory location denoted by the address
     * stored in 'd', you will not be anymore access 
     * the contents of it.
     */
    free (d);

    /* d->b; or d->a; is no more possible at this point
     * as we have freed the memory pointed by 'd'
     */
}

Or you can use:

int main()
{
    /* Not a pointer, statically allocated */
    struct data d;
    int *ptr;

    int key=10000;
    d.b=&key;

    ptr=(int *)d.b;
    printf("%d\n",*ptr);
}

So, it is not the typecasting of void * to int * that causes the segfault. Its the illegal memory reference of the pointer variable which you have used but not allocated/initialized.


The problem is that you didn't allocate memory for a d pointer: struct data *d;. This lines only creates a pointer, it doesn't alloc memory for it. Please try the following code:

int main()
{
    struct data *d = (struct data*)malloc(sizeof(struct data));
    int *ptr;
    int key=10000;
    d->b=&key;
    ptr=(int *)d->b;
    printf("%d\n",*ptr);
    free(d);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜