What is the behavior of the following code?

#include <stdio.h> 
#include <stdlib.h>

struct node { 

    int data; 
    struct node *next;
}; 
struct node* insert(struct node *root) {

    root->data = 12; //here
    return root; 
}
int main() {

    struct node *root;
    insert(root);
    return 0; 
}

Shouldn't my program crash at the place where I have placed the comment in the insert function because I have not initialized it with malloc?

Upvotes: 0

Views: 95

Answers (2)

dbbbit
dbbbit

Reputation: 1

just add a printf to make some test:

printf("root is %p\n", root);

some results:

Airbus /tmp » ./a.out
root is 0x7fff50b84a08
Airbus /tmp » ./a.out
root is 0x7fff5d1a6a08
Airbus /tmp » ./a.out
root is 0x7fff5ed7da08
Airbus /tmp » ./a.out
root is 0x7fff5c7f5a08
Airbus /tmp » ./a.out
root is 0x7fff5fb3aa08
Airbus /tmp » ./a.out
root is 0x7fff5c16ea08
Airbus /tmp » ./a.out
root is 0x7fff579a8a08

Apple LLVM version 6.1.0 (clang-602.0.49) (based on LLVM 3.6.0svn)

and i got segmentfault in my gentoo:

[1]    8390 segmentation fault

gcc version 4.5.4 (Gentoo 4.5.4 p1.2, pie-0.4.7)

Upvotes: -1

Gopi
Gopi

Reputation: 19864

This is called undefined behavior You never know what might happen.Crash is still a possibility.

Using uninitialized variabled lead to undefined behavior.

Upvotes: 3

Related Questions