-4

I'm not sure why the following is producing a segmentation fault. I've defined a structure and I'm trying to store a value to it.

typedef struct {
    int sourceid;
    int destid;
} TEST_STRUCT;

void  main( int argc, char *argv[] )  {
    TEST_STRUCT *test;
    test->sourceid = 5;
}
turtle101
  • 359
  • 1
  • 2
  • 7

2 Answers2

2

You declare a pointer to the type. You need to allocate memory for the pointer to point to:

#include <stdlib.h>

typedef struct {
    int sourceid;
    int destid;
} TEST_STRUCT;

int main(int argc, char *argv[])  {
    TEST_STRUCT *test;
    test = malloc(sizeof(TEST_STRUCT));
    if (test) {
        test->sourceid = 5;
        free(test);
    }
    return 0;
}

Alternatively, you could declare the variable on the stack:

typedef struct {
    int sourceid;
    int destid;
} TEST_STRUCT;

int main(int argc, char *argv[])  {
    TEST_STRUCT test;
    test.sourceid = 5;
    return 0;
}
1

test pointer is not pointing to any address(pointing some garbage) so it is hitting segV

 TEST_STRUCT *test;

it is good practice to initialize NULL and before dereference it, check if (test != NULL) {} then only dereference.

to solve this, first you need to create variable of TEST_STRUCT and assign address of it to test pointer or allocate memory using malloc/calloc and then try this

ShivYaragatti
  • 398
  • 2
  • 8
  • When formatting, you can enclose inline code in backticks, e.g. `\`...\`` to format as code (fixed font with off-color background) An example of *"you need to create variable of TEST_STRUCT and assign address of it to test"* would also be nice. – David C. Rankin Dec 15 '18 at 03:44
  • @DavidC.Rankin Thank you for educating, I will improve on it :-) – ShivYaragatti Dec 15 '18 at 03:55
  • Yep, I know, just trying to help you along. Good luck on S.O. and with your coding. – David C. Rankin Dec 15 '18 at 03:58