Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 310
spyros pikoulas Avatar asked Apr 07 '26 00:04

spyros pikoulas


1 Answers

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".)

like image 105
Mike Nakis Avatar answered Apr 09 '26 20:04

Mike Nakis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!