运行时分段错误 [英] segmentation fault error in run time

查看:118
本文介绍了运行时分段错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我为树写了一个程序

i write a program for tree

#include<stdlib.h>
#include<malloc.h>
#include<conio.h>

struct tree
{
    int data;
    struct tree *left;
    struct tree *right;
};

void add(int x)
{
    struct tree *root;
    root=(struct tree*)malloc(sizeof(struct tree));

    root->data=x;
    root->left=NULL;
    root->right=NULL;

    printf("%d",root->data);

    root=root->left;
    root->data=3;
    root->left=root->right=NULL;
    printf("%d",root->data);

}

int main()
{



        add(2);

        return 0;
}


它在ubuntu 12.04中给出错误分段错误(核心已转储)
我在程序中使用root = root-> left时出现问题
如何运行此程序


it give error segmentation fault (core dumped) in ubuntu 12.04
problem when i use root=root->left in program
how to run this program

推荐答案

您的程序在我的系统上运行得很好(应按要求运行)(LinuxGCC 4.4.5).
但是,它会泄漏内存(malloc从未与free配对).

[更新]
请参阅Richard的回答.
[/UPDATE]
Your program is runningwfine (as it should) on my system (Linux with GCC 4.4.5).
However, it leaks memory (malloc is never paired with free).

[UPDATE]
Please see Richard''s answer.
[/UPDATE]


root=root->left;
root->x=3;


它将root设置为NULL,但是该结构不包含名为x的元素,因此甚至不应编译.尝试使用复制和粘贴来发布给出错误的确切代码.


That sets root to NULL, but the structure does not contain an element named x so this should not even compile. Try using copy and paste to post the exact code that gives the error.


这篇关于运行时分段错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆