r/C_Programming • u/Yousef_Tele • Jul 16 '26
Why does it show me a segfault?
When I compile the code without any compiler flags, I see a segmentation fault. Why?
static int linked_init(struct list_t *list)
{
if(linked_init)
list->head = list->tail = NULL;
else
return -1;
return 0;
}
int main()
{
linked_init(NULL);
}In the `init` function, I checked for a null pointer.
UPDATE: Sorry to everyone, I made a fucking bad mistake. My problem is solved.
38
Upvotes
2
u/TPIRocks Jul 16 '26
You updated the post to tell us you fixed it, but not what is wrong, why would you do that?
45
u/Modi57 Jul 16 '26
In your if condition, you check if
linked_initis not null. It should belistinstead20
u/RealisticDuck1957 Jul 16 '26
For future seg fault bugs:
- compile with debug symbols enabled.
- run inside a debugger. This will tell you exactly where in the code a seg fault is realized. And facilitate inspection of what's going on before that line of code executes.
13
u/umlcat Jul 16 '26
// you made a mistake:
static int linked_init(struct list_t *list)
{
if(list != NULL)
list->head = list->tail = NULL;
else
return -1;
return 0;
}
9
u/ReallyEvilRob Jul 16 '26
2
u/Alduish Jul 16 '26
So in the if you put the wrong thing, you should put if(list != NULL).
Right now it's if(linked_list) with linked_list being a function so if the function pointer isn't NULL (which it isn't since it points to an existing function) you try to de-reference list which is NULL, that causes a segfault
2
u/grigus_ Jul 16 '26
You have a mistake. I would write if(list != NULL)
1
u/Ok_Chemistry_6387 Jul 16 '26
I am genuinely interested in why compiling with flags changed the behaviour. Were you compiling with optimisations previously?
1
u/Living_Fig_6386 Jul 20 '26
You can't dereference NULL. You're doing
NULL->head = NULL->tail = NULLDid you mean
if (list)in the function?-16
u/cbf1232 Jul 16 '26
You need to test the value of 'list', not 'linked_init'.
Next time ask an LLM first.
-4
u/[deleted] Jul 16 '26
[removed] — view removed comment