You gotta love undefined behavior. (C)

Hi!
I just entered the lands of Undefined bahavior ^^

here is the story:
I was writing a short code (only about 100 lines)
and as it was just some kind of 'quick and dirty' thing, I did not looked to closely what i did. anyway I had the first version running, and got no errors.

then I wanted to add something. but the code unexpectedly crashed. (some pointer mess)
So when I searched for the bug i only looked at the differences to the first version, as the first version was running smoothly.
I found out that the first version runs smoothely until I added another Variable declaration.
that was kind of an 'wtf?' moment.
I looked over the code again, and did not find anything. Instead of posting the code here and make another "help my I'm stupid"-thread, I slept a night over it.

here is the error:

C-code a little fukced to make it easier to read. and left out unimportant stuffs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38

typedef struct{
 char c;
 void *next;
}linked;

int funktion(){
 linked root;
 root.c=0;
 root.next=NULL;
 linked* current=NULL;
 linked* prev=NULL;
 current=&root;
 current->c=getc();
 while(!isspace(current->c)){ 
  current->next=malloc(sizeof(linked));
  current=(linked*)current->next;
  current->next=NULL;
  current->c=0;
  current->c=getc();
 } //so basicaly reads a string from stdin into a linked list
 //some random codestuffs here
 current=&root;
 while(current->next!=NULL){
  prev=current;
  current=current->next;
  free(prev);
 }
 free(current);
 return 0;
}

int main(){
 while(some condition){
  funktion();
 }
 return 0;
}


as one can easily see:

1
2
3
4
 linked root;
 current=&root;
 prev=current;
 free(prev);

-> undefined behavior

just wanted to share my stupidity with someone who understands it XD
Last edited on
Topic archived. No new replies allowed.