[Solved] Learning C, segfailt confusion


You should build your code with -Wall flag to compiler. At compile time it will then print:

main.c:9:15: warning: ‘coord1’ is used uninitialized in this function [-Wuninitialized]

This points you to the problem.
coord1 is a pointer type, that you assign to, but coord1 has no memory backing it until it is initialized. In the following snippet coord1 is initialized by allocating memory to store it’s components. This gets rid of the segfault.

VECT coord1 = NULL;

coord1 = (VECT)malloc(sizeof(struct vector));
if (NULL == coord1)
{
    fprintf(stderr, "Out of memory!\n");
    exit(1);
}

coord1->x = 0.0012345;
coord1->y = 0.012345;
coord1->z = 0.12345;

In general, segfaults happen when a program accesses memory that the operating system has not allocated to it. Unintialized pointers usually point to address zero, which is not allocated to any program. Always use gcc -Wall when compiling, this will many times point to these potential problems. Helped me find it right away.

Also, you could have declared your VECT type to be typedef struct vector (a non-pointer type).

VECT coord1;
VECT* v_coord1 = &coord1;
v_coord1->x = 0.0012345;
v_coord1->y = 0.012345;
v_coord1->z = 0.12345;`

Also, variable naming conventions can help here as well.

struct vector{
    double x;
    double y;
    double z;
 };

typedef struct vector VECT;
typedef struct vector* pVECT;

1

solved Learning C, segfailt confusion