spyros pikoulas
spyros pikoulas

Reputation: 39

structs and segmentation fault

#include<stdio.h>
#include<stdlib.h>
main()
{
    typedef struct tnode *pad;
    struct tnode{
    int data;
    pad left;
    pad right;
    };
    pad p=NULL;
    p=malloc(sizeof(struct tnode));
    (p->data)=5;
    (p->left)=malloc(sizeof(struct tnode));
    (p->left)->data=4;
    (p->right)=malloc(sizeof(struct tnode));
    (p->right)->data=7;
    printf("\nroot is %d right %d left %d",p->data,(p->left)->data,(p->right)->data);

I ran this code and I got a segmentation fault The code isn't doing something specific, I am just wondering why the segmentation fault.

Upvotes: 3

Views: 99

Answers (2)

Mike Nakis
Mike Nakis

Reputation: 61949

I tried running it on ideone.com and it works fine, (the printf() function prints what it is supposed to print,) then afterwards it gives a "Runtime error".

Then I added a "return 0" at the end and it works fine without any error.

Supply the right arguments to the compiler to have it give you proper warnings for a multitude of common programming errors. In your case, you specified your main() function incorrectly, (it is supposed to return 'int',) but the compiler was compiling it in traditional C mode, so it did not warn you about that. Then, since the prototype was missing a return type, the compiler did not warn you that you were missing a return statement, either. You will save yourself from a lot of trouble if you start using -Wall (or whatever other flag your compiler understands as "enable all warnings".)

Upvotes: 1

Gopi
Gopi

Reputation: 19864

Your code looks good and the only reason you might see a crash is because the malloc() might have failed and you are trying to access the unallocated memory.

p=malloc(sizeof(struct tnode));

if( p != NULL)
{
   //Do your stuff
}
else
return 1;

Similarly check the return values for the rest of your malloc() and once done using the memory please do free it free(p)

PS: main() should be int main()

Upvotes: 0

Related Questions