简体   繁体   English

结构和分段错误

[英]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. 我运行这段代码,我得到了一个分段错误代码没有做一些特定的事情,我只是想知道为什么分段错误。

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". 我试着ideone.com运行它,它工作正常,(在printf()函数打印什么是应该打印,),那么以后它给出了一个“运行时错误”。

Then I added a "return 0" at the end and it works fine without any error. 然后我在结尾添加了一个“返回0”,它没有任何错误。

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. 在你的情况下,你错误地指定了你的main()函数(它应该返回'int'),但是编译器在传统的C模式下编译它,所以它并没有警告你。 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".) 如果你开始使用-Wall (或编译器理解为“启用所有警告”的任何其他标志),你将免于很多麻烦。)

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. 您的代码看起来很好,并且您可能看到崩溃的唯一原因是因为malloc()可能已经失败并且您正在尝试访问未分配的内存。

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) 同样检查malloc()的其余部分的返回值,一旦使用内存完成,请免费free(p)

PS: main() should be int main() PS: main()应该是int main()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM