不同OS时的分段故障

时间:2013-04-20 18:57:26

标签: c segmentation-fault portability

我有一个C项目,我对C和Linux环境都很陌生。

我正在使用以下系统信息开发Linux发行版

  

Linux bt 3.2.6#1 SMP Fri 2月17日10:34:20 EST 2012 x86_64 GNU / Linux

在用gcc编译之后,在上述操作系统上,我得到了等待的结果。

在将我的项目提交给教授之前,我想过尝试使用以下系统信息在另一个Linux发行版上编译和执行该程序

  

Linux feistyFawn 2.6.20-15-generic#2 SMP Sun Apr 15 07:36:31 UTC 2007   i686 GNU / Linux

在这个下我得到了分段错误。 为了说明输出控制台。这是图像。

作品

enter image description here

失败

enter image description here

我不知道现在该做什么。


代码

调用此函数会导致另一个操作系统出现分段错误。

fileInEvenements(listEvents, 'A', time, queueId);

它的作用是将名为A的事件中的文件存入队列结构listEvents。

及其定义

void fileInEvenements(eventStructure *listEvents, char eventType, int time_exec, int id_queue)
{
    Event *newEvent = malloc(sizeof(*newEvent));
    if (newEvent == NULL || listEvents == NULL){
        exit(EXIT_FAILURE);
    }

    newEvent->type = eventType;
    newEvent->execution_time = time_exec;
    newEvent->id = id_queue;
    if (listEvents->firstEvent != NULL)
    {
        // the list contains at least one event, go to the end of list 
        Event *evCurrent =  listEvents->firstEvent;
        while (evCurrent->next != NULL)
        {
            evCurrent = evCurrent->next;
        }
        evCurrent->next = newEvent;
    }
    else // the list contains no event, new event becomes first event
    {
        listEvents->firstEvent = newEvent;
    }

}

2 个答案:

答案 0 :(得分:3)

当您在链接列表中创建新条目时,您试图通过从头开始并迭代列表将其附加到列表中,直到您在NULL中找到evCurrent->next。如果找到NULL,则停止迭代列表,然后通过newEventevCurrent->next = newEvent;指定为列表中的下一个条目 - 当然,如果没有在链接列表中的条目,您通过listEvents->firstEvent = newEvent;

将新条目作为列表的头部

但是,您在任何时候都没有初始化newEvent->next的值。请注意,malloc()不会初始化它返回的内存块。它只是分配一个块并将其返回给您。请参阅此处的文档http://www.cplusplus.com/reference/cstdlib/malloc/

关键是这......

  

新分配的内存块的内容初始化,   保持不确定的价值。

因此,newEvent->next实际上是一个随机值。因此,您的代码将进入随机内存遍历,因为您指望它是NULL来终止链接列表。

我建议您尝试使用calloc()

Evenement *newEvent = calloc( 1, sizeof(*nvEvent) );

否则,请确保在创建next元素时将其初始化为NULL

答案 1 :(得分:1)

添加一行:

newEvent->next = NULL;

使用未初始化的字段是错误的。

或者您可以使用以下内容:

newEvent = calloc(sizeof(*newEvent), 1); // instead of malloc

或者

memset(newEvent, 0, sizeof(*newEvent)); // set all fields to 0
相关问题