现在的位置: 首页 > 综合 > 正文

我的程序段错误的研究

2012年10月22日 ⁄ 综合 ⁄ 共 2208字 ⁄ 字号 评论关闭

本来就是一个很简单的问题,但是我花了一个半小时,要是没有gdb这个东西那我真的是以为是我的linux的问题,其实菜鸟就是这个样子的啊,出了问题就怪系统,做人的时候出了问题就不要怪别人啊。

呵呵,废话少说,go

先看程序:film.c

 #include <stdio.h>
#include <stdlib.h>      /* has the malloc prototype      */
#include <string.h>      /* has the strcpy prototype      */
#define TSIZE    45      /* size of array to hold title   */

struct film {
    char title[TSIZE];
    int rating;
    struct film * next;  /* points to next struct in list */
};

int main(void)
{
    struct film * head = NULL;
    struct film * prev, * current;
    char input[TSIZE];

/* Gather  and store information          */
    puts("Enter first movie title:");
    while (gets(input) != NULL && input[0] != '/0')
    {
        current = (struct film *) malloc(sizeof(struct film));
        if (head = NULL)       /* first structure       */
            head = current;
        else                    /* subsequent structures */
            prev->next = current;
        current->next = NULL;
        strcpy(current->title, input);
        puts("Enter your rating <0-10>:");
        scanf("%d", &current->rating);
        while(getchar() != '/n')
            continue;
        puts("Enter next movie title (empty line to stop):");
        prev = current;
    }

/* Show list of movies                    */
    if (head =NULL)
        printf("No data entered. ");
    else
        printf ("Here is the movie list:/n");
    current = head;
    while (current != NULL)
    {
        printf("Movie: %s  Rating: %d/n",
               current->title, current->rating);
        current = current->next;
    }

/* Program done, so free allocated memory */
    current = head;
    while (current != NULL)
    {
        free(current);
        current = current->next;
    }
    printf("Bye!/n");

    return 0;
}

这个程序调试是完全没有问题的,但是运行到输入一个字符串以后就会出现段错误,无敌了,开始以为是malloc的错误,跑到stdlib库函数去查了一下他的使用方法,还是不行,真的郁闷。

弄了好久,才想到gdb这个东西,其实我平时我的程序只要可以通过就一般不用gdb,菜鸟的见地哈。gcc -g之后成功编译,然后gdb,再file film,b main,run,s,一直s下去,就可以看到发生问题的程序句子:

        if (head = NULL)       /* first structure       */
            head = current;
        else                    /* subsequent structures */
            prev->next = current;

我在刚刚开始输入的时候,应该正确的执行的       

 if (head = NULL)             

   head = current;

但是我看到的却是:

        if (head = NULL)   
        prev->next = current;

想了好久,不可能啊,执行的顺序不对啊,哦,=不对,因改是==,null赋值给head之后就是head=0,那么相当于if(head)了,又相当于if(0)了,那么执行的是就是else里面的句子了。

下面还有一个一样的逻辑错误,c语言的设计就是这样,他不会检测逻辑错误的。其实上面大 两个错误都很简单的,高手以平常心态看程序的时候一看就晓得,但是人一旦被迷惑了,就只有借助gdb了

学会使用gdb,学会把握自己的程序。

抱歉!评论已关闭.