0

I am rather new to C and although this code compiles (using gcc -Wall -o test test.c), running ./test just results in the output dbecher$: Segmentation fault: 11. Does anybody know what might cause this?

Well, I know instead of using a pointer I could just assign a normal struct, but I am using this to test some behavior of pointers. So I want to keep using a pointer variable for that struct.

Here the code snippet:

#include <stdio.h>

typedef struct HumidityMessage {
  int nodeId;
  int sequenceNumber;
  int humidity;
} HumidityMessage;

HumidityMessage* packet;

int main() {
    packet->nodeId = 0;
    packet->sequenceNumber = 1;
    packet->humidity = 3;

    printf("This is the address of packet: %d", packet->nodeId);
}
1
  • Global variables are initialized to 0. Hence, packet is a null pointer. And then you are trying to dereference it. Commented Apr 24, 2015 at 12:32

4 Answers 4

4

Segmentation faults are caused by invalid memory accesses. In this case you're getting it because you're dereferencing the packet pointer without first allocating space for it.

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

Comments

2

HumidityMessage* packet; is pointing to nothing. Initialize it:

HumidityMessage* packet = malloc(sizeof(HumidityMessage));

4 Comments

No, it's global so it's initialized to 0.
it's not pointing to garbage. it's NULL because it's global.
Actually that is what i wrote before - then got confused then corrected myself again lol.
Ah! of course, I totally forgot that in the beginning the pointer is pointing pretty much to nothing!
1

Don't use a pointer. Use HumidityMessage packet; instead.

Currently packet is initialised to nullptr and it's illegal to dereference that.

Alternatively you could retain the pointer and allocate memory for it before you need it, but finding a place for the corresponding free is problematic for globals.

Comments

0

Allocate memory to the packet pointer using the c inbuilt malloc function. Packet = (HumidityMessage * )malloc(size of(HumidityMessage)); Or you can directly take a variable of the structure and assign the value.

1 Comment

in C, do not cast the returned value from malloc() (and family of function)

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.