【问题标题】:c code file is crashing and there is no error while compile [closed]c代码文件崩溃并且编译时没有错误[关闭]
【发布时间】:2018-12-28 04:59:27
【问题描述】:

我在我的代码上做的一切都是正确的,但仍然有一个我不知道为什么的问题

#include<stdio.h>
#include<stdlib.h>
struct node { 
    int data ; 
    struct node* link ; 
};
struct node* top = NULL ;
void pop(){ 
    if(top==NULL) 
        printf("element that will delete is %d\n",top->data);
    else {
        struct node* temp ;
        temp= top ; 
        top = top->link ;
        temp->link = NULL ; 
        free(temp);
        }}
void push() { 
    struct node* temp ;
    temp =(struct node*) malloc(sizeof(struct node ));
    printf("please enter the data of the first node \n"); 
    scanf("%d",&temp->data);
    temp->link = top ; 
    temp = top ; 
} 
void printx(){
    if(top==NULL)
        printf("there is no element to print\n");
    else { 
        struct node* temp ; 
        while(temp != NULL) {
        printf("%d\n",temp->data) ;
        temp = temp->link ; 
        }


    }
}
int main() { 

    printf("please enter the type of operation u want to perform\n") ;
    printf("enter 1 for push , 2 for pop , 3 for print:  ") ;

    int x ; 
    scanf("%d",x) ; 
    switch(x){
        case 1 :    
            printf("\nu choosed push\n");
            push(); 
            break ; 

        case 2 :    
            printf("u choosed  pop \n"); 
            pop() ; 
            break ;

        case 3 :    
            printf("u choosed to print the element of the stack\n") ;
            printx(); 
            break ; 

    }

}

【问题讨论】:

  • 寻求调试帮助的问题(“为什么这段代码不起作用?”)必须包括所需的行为、特定的问题或错误以及在问题本身中重现它所需的最短代码。没有明确问题陈述的问题对其他读者没有用处。
  • 在流行音乐中你有这个代码:if(top==NULL) printf("element that will delete is %d\n",top-&gt;data);。取消引用 NULL 指针肯定会崩溃。
  • 没有编译器错误?肯定是关于scanf("%d", x); 的警告吗?这应该是scanf("%d", &amp;x);
  • 感谢您的认可。
  • @bruceg 不,不是。这是未定义的行为,这意味着。无法保证会发生什么。在 CP/M 下用 BDS C 编译它,当你取消引用 NULL 指针时它绝对不会崩溃。

标签: c crash


【解决方案1】:

如果您将此代码粘贴到 https://www.onlinegdb.com/ ,然后单击“调试”,然后在 gdb 窗口中键入 run,它会将您带到创建错误的行。 (您可以单击“调试”按钮附近的“帮助”按钮以获取有关如何进一步使用此工具的说明。或者您可以谷歌“gdb 调试”或“Visual Studio 调试”以获得更多帮助。)

错误在您的scanf 行。如果你用谷歌搜索“scanf”,你可能会注意到 int 参数传递了 address of int。所以你需要&amp;x,而不是x。您的程序也有其他错误。我建议你使用上面提到的调试器的帮助按钮,单步调试你的程序,然后观察发生了什么。例如,您会注意到,一旦您解决了第一个问题,您的程序就会立即退出。我想你会想要一个循环来防止这种情况。此外,在您的流行音乐中,您专门检查是否为top==null,如果是,则取消引用它(top-&gt;data)。这保证是非法的。您可以通过运行调试器、选择 pop,然后打印程序尝试访问的值(在调试器中)(gdb 窗口中的print top-&gt;data)来检查这一点

【讨论】:

  • 您重复了一条评论,但更原始的可能是您提到的“其他错误”。
  • @WeatherVane - 是的,我会考虑将 OP 指向调试资源,这是这个答案的主要贡献。 IMO 这显然是需要的,因为武断地指出各种问题而没有暗示人们如何找到它们不太可能有帮助。我确实稍微修改了我的答案。
  • 这是一个很好的尝试,但有关调试的提示和链接并不能回答问题。
  • @WeatherVane - 好吧,还有一个答案。不知道除了我调试整个程序之外还需要什么。
  • @WeatherVane - 抱歉——我非常生气,因为人们对这个问题的废话投了反对票,尽管这对于经验丰富的程序员来说是完全合理的,但基本上没有提供任何帮助。我的回答远非完美,但它击败了投票,简短的 cmets 对操作可能几乎不理解或尖刻且根本没有帮助的问题。无论如何,重点是对简短的回应表示歉意......并不是真的针对你。
猜你喜欢
  • 2013-01-12
  • 1970-01-01
  • 1970-01-01
  • 2011-06-08
  • 2016-02-14
  • 1970-01-01
  • 2014-09-25
  • 2017-09-20
  • 1970-01-01
相关资源
最近更新 更多