0

I'm trying to run this code. If it is ran like this it works, but as soon as the second struct is uncommented it fails with a "Segmentation fault: 11". What am I doing wrong here?

#include <stdio.h>

void func();

typedef struct foo
{
    double one;
    double two;
} foo;


int main() {

    func();
    printf("ret");

    foo *f;
    f->one = 10;
    f->two = 10;

//    foo *g;
//    g->one = 10;
//    g->two = 10;


return 0;
}
förschter
  • 740
  • 1
  • 7
  • 24

3 Answers3

3

You probably intended to do this:

foo f;
f.one = 10;
f.two = 10;

Here f is not a pointer to a foo but it is a foo.

When you write foo *f;, then f is a pointer, and you need to assign a valid memory address to it before you can dereference it, for example as in Marievi's answer.

You should probably read the chapter dealing with pointers in your C text book.

Jabberwocky
  • 48,281
  • 17
  • 65
  • 115
  • wow I did not realise that this was the mistake. I have had a rather brief introduction to C, I'll take another look at the chapter about pointers. – förschter Oct 17 '17 at 15:09
2

You declare pointer foo but you also need to allocate memory for it :

foo *f = malloc(sizeof(struct foo));
if (f == NULL)
    return;

because right now, you have it uninitialized but try to de-reference it.

Marievi
  • 4,951
  • 1
  • 16
  • 33
0

UB warning!!!

Here - foo *g; you only declare a pointer. It points to memory you don't yet own (haven't malloc() it). Trying to de-reference such a pointer is UB and can cause (in your case does cause, a segfault).

Note that the same goes for your foo *f;. malloc() both and them.

Oh, and READ COMPILER WARNINGS!! (warning: 'g' is used uninitialized in this function)

Two ways to fix this:

  1. don't use pointers... change foo *g; into foo g and g->one = 10 into g.one = 10. in this case, the memory is allocated to you on declaration
  2. allocate memory... add this line g = malloc(sizeof(*g)); after foo *g; (and also after foo *f). _here, the memory is allocated by you and would have to be released afterwards by you!! (using free(g); )
CIsForCookies
  • 12,097
  • 11
  • 59
  • 124