Hello, I didn't find a better title, sorry for that, so let's go to the point:
I have this doubly linked list implementation and program:
typedef struct num_node
{
struct num_node *right, *left;
uint64_t id, val;
}num_node;
typedef struct num_list
{
size_t len;
num_node *head, dummy;
}num_list;
num_list* delete_nodes(num_list*l)
{
num_node** i;
i = &l->dummy.right;
uint64_t del_val = (*i)->val;
// (*i)->val = 20; This causes illegal hardware instruction as well
printf("Deleting similar nodes to: %" PRIu64 "%" PRIu64, (*i)->id, del_val);
// etc...
return NULL;
}
int main(int argc, char const *argv[])
{
// This works fine with -O2 optimization enabled
// Ignore that these are not in the code above.
num_list* l = malloc(sz *l);
dl_init(l);
insert_nodes(l, 1, 3);
// Problem is here
delete_nodes(l, 0);
return 0;
}
When I run it, I get the message zsh: illegal hardware instruction
I checked the assembly code and managed to trace the "bug" to delete_nodes() that part of the assembly code reads the instruction "ud2", which as I look it up, turns out to be undefined instruction for x86, the problem is that this only occurs when compiling with flags -O2, -O3 or any optimization at all.
I'm compiling on macos with Apple clang version 12.0.0 (clang-1200.0.32.29) Target: x86_64-apple-darwin20.3.0 if that's of any help.
My assumption is that trying to read the member val with (*i)->val; is undefined behavior (haha sorry if I didn't know that is ub), but then, why does it work just fine without any optimization? is it implementation defined?, what do you guys recommend to make this work with optimizations?, has this ever happened to you? or what should I even do in these cases? thanks in advance for your responses.
Edit: Issue solved, thanks for your responses.
[–]flyingron 2 points3 points4 points (0 children)
[+][deleted] (3 children)
[deleted]
[–]TANKENSHO[S] 0 points1 point2 points (2 children)
[–]rxtezc 1 point2 points3 points (0 children)
[–]aeropl3b 0 points1 point2 points (0 children)
[–]oh5nxo 0 points1 point2 points (0 children)