tags:

views:

58

answers:

4
int d() {return 0;} int i() {return 7;}

struct a { int(*b)(); }c={d};

typedef struct e{ struct a f; }g;

main() { struct e *h; h->f.b = i; }

I am getting segmentation fault when I try to run this program. Can anyone justify the reason?

And I also tried like

int d() {return 0;} int i() {return 7;}

struct a { int(*b)(); }c={d};

typedef struct e{ struct a f; }g;

main() { struct e *h; h = (g)malloc(sizeof(g)); h->f.b = i; }

Now I am getting errors like

funptrinstrct.c: In function `main': funptrinstrct.c:17: error: conversion to non-scalar type requested

Answer for this also would be appreciable.

A: 

h is an uninitialized pointer.

Trying to dereference it is a big no-no

Bwmat
A: 

struct e *h is an undefined pointer, either declare it on the stack by dropping the '*' or allocate it with malloc.

Mattias Holm
+5  A: 

For the first question, you create a pointer h without initialising it, then you immediately try to dereference it with h->f.b.

For the second one, you should be casting to g*, not g:

#include <stdio.h>

int d (void) { return 0; }
int i (void) { return 7; }

struct a { int(*b)(void); } c = {d};
typedef struct e { struct a f; } g;

int main (void) {
    struct e *h = (g*)malloc (sizeof (g));
    h->f.b = i;
    printf ("%d\n", h->f.b());
}

That's because g is a structure, not a pointer to a structure. The code above outputs 7 as expected.

paxdiablo
A: 

change your main body to

struct e *h = (struct e *)malloc(sizeof(struct e)); 
h->f.b = i;

It will work. moral:

Never ignore warnings

.

alam
You can still use `g` just fine, the problem was simply that it wasn't a pointer being cast to. And your moral (however condescending) is irrelevant since it was an error, not a warning. Hard to ignore something that won't give you executable code :-)
paxdiablo
For first case it gives warning
alam
Right, that's me sorted then. Apologies for that :-)
paxdiablo