1
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.

4 Answers 4

5

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.

Sign up to request clarification or add additional context in comments.

Comments

0

h is an uninitialized pointer.

Trying to dereference it is a big no-no

Comments

0

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

Comments

0

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

.

3 Comments

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 :-)
For first case it gives warning
Right, that's me sorted then. Apologies for that :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.