asdf
asdf

Reputation: 667

Pointer to a struct

I'm trying to understand pointers more and am having trouble with this example.

 typedef struct{
    int areaCode;
    int streetNumber;
 }Address;
 Address *addr;
 addr->areaCode = 10000;
 printf("%d\n", addr->areaCode);

I get a segmentation fault and can't seem to understand why.

addr is a pointer to a Address struct, so I also tried:

 *addr->areaCode = 10000;

and also got a "indirection requires pointer operand ", any ideas?

Upvotes: 0

Views: 78

Answers (3)

Baldrickk
Baldrickk

Reputation: 4409

addr is uninitialised and so contains some 'random' value. De-referencing an uninitialised pointer causes... problems.
Accessing memory that you are not allowed to = segmentation fault.
Accessing random memory that doesn't seg-fault leads to memory corruption.

You can do:

Address myAddress;
Address *addr = &myAddress;

and this will work. Allocate first then aquire pointer.
This will produce a pointer to the Address on the stack. Beware of it going out of scope at the end of the function.

You can also do:

Address *addr = malloc(sizeof(Address));

This allocates on the heap so the actual Address won't go out of scope. But you do need to remember to free(addr); or you introduce a memory leak.

Upvotes: 1

Grzegorz Szpetkowski
Grzegorz Szpetkowski

Reputation: 37914

You haven't allocated memory for structure object. Either use malloc() or simply declare variable of type Address instead of pointer to Address (in which case to access member use . operator instead of ->).

Option one:

Address *addr = malloc(sizeof *addr); // don't forget #include <stdlib.h>
if (addr == NULL) {
    // handle failed allocation
}
// ...
free(addr); // free(addr), addr = NULL; if you like

Option two:

Address addr;

Upvotes: 1

timrau
timrau

Reputation: 23058

Address *addr;

You only declared a pointer addr, but it points to somewhere unknown. You didn't allocate memory space for it.

To fix it, change into

Address *addr = malloc(sizeof(Address));

Upvotes: 4

Related Questions