jjzjj

C++ 链表仅在 GNU/Linux 而不是 Windows 中导致段错误

coder 2023-11-12 原文

下面是我正在进行的练习中的代码片段。它读取 CSV 并将其输入链表,然后打印到控制台。 CSV 看起来像这样:

5,3,19
7,12,2
13,15,25
22,0,7

它在 Linux 和 Windows 中使用 Visual Studio 2010 和 G++ 进行编译。二进制文件在 Windows XP 命令提示符下执行,但在 Git Bash (Windows XP) 和 Linux 下运行时会出现段错误。使用调试器(在 Linux 下),我将问题隔离到 printList() 无法识别链表的末尾。

为什么会发生这种情况,我该怎么做才能防止这种情况发生?任何建议将不胜感激。

#include <cstdlib>
#include <sstream>
#include <iostream>
#include <fstream>

using namespace std;

// CSV source file parameters
const char *cSourceCSV = "source.csv";
const int iFieldsPerRow = 3;

enum direction_t {UP=1, STATIONARY=0, DOWN=-1};

// struct to hold data in a singly linked list
struct CallList {
  float fTime; // time of call in seconds from beginning
  int iFromPos;
  int iToPos;
  direction_t d_tDirectionWanted();
  CallList *next;
};

direction_t CallList::d_tDirectionWanted() {
  int iBalance = iFromPos - iToPos;
  direction_t d_tDirection;
  if (iBalance < 0) d_tDirection = DOWN;
  else if (iBalance == 0) d_tDirection = STATIONARY;
  else if (iBalance > 0) d_tDirection = UP; 
  return d_tDirection;
}

CallList *head;
CallList *temp;
CallList *work;

void populateList(const char *cSourceCSV) {
  string sRow;
  string sValue;
  ifstream ioSource (cSourceCSV); // the source file placed in an input stream 
  if (ioSource.is_open()) { // making sure the stream/file is open
while (ioSource.good()) { // repeat while stream is still healthy
  // obtain the data
  temp = new CallList;
  getline (ioSource,sRow); // reading each row of data
  stringstream s_sRow(sRow); // now entering the row into a stringstream
  for (int i=0; i<iFieldsPerRow; i++) { 
    ws(s_sRow); // if there is whitespace in s_sRow remove it <-this is 
        // stopping the program from crashing but I get an extra line 1,1,1
    getline (s_sRow,sValue,','); // now getting the data from the 
                // stringstream using the comma as a delimiter
    if (i==0) {
      temp->fTime = stof(sValue);
    }
    else if (i==1) { 
      temp->iFromPos = stoi(sValue);
    }
    else if (i==2) {
      temp->iToPos = stoi(sValue);
    }
  }
  // the stationary calls are excluded
  if (temp->d_tDirectionWanted() == STATIONARY) continue;

  // place the remaining data in the linked list
  if (head == NULL) {
    // insert the head
    head = temp;
  }
  else {
//********* THIS WORKS *************
    work = head;
    // nothing fancy needed here as list is already in time order
    while(work != NULL) {
      if (work->next == NULL) {
    work->next = temp;
    break;
      }
      work = work->next;
    }
  }
//************************************
}
ioSource.close();
  }
  else cout << "Error opening file: " << cSourceCSV << endl;
  return;
}

//********* BUT THIS DOESN'T, WHY? *************
void printList(){
  work = head;
  while (work != NULL) {
printf("Time: %*.1f, From: %*i, To: %*i, Dir: %*i\n", 5, work->fTime, 2, work->iFromPos, 2, work->iToPos, 2, work->d_tDirectionWanted());
if (work->next == NULL) break;
else work = work->next;
  }
  return;
}
//************************************


int main(int argc, char *argv[]) {
  populateList(cSourceCSV);
  printList();
  return 0;
}

最佳答案

第一次分配 CallList 节点时,将 next 字段设置为 null。

temp = new CallList;
temp->next = NULL;

您的 printList 遍历列表,直到 workNULLwork 获取其值从未初始化的列表节点的 next 字段。当它结束时,最后一个节点在 next 字段中包含垃圾,您的程序就会终止。

为什么这在 Windows 上是 OK 而不是在 Linux 上是未定义行为的产物,当您尝试访问未初始化的变量时会得到这种结果。

关于C++ 链表仅在 GNU/Linux 而不是 Windows 中导致段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13042389/

有关C++ 链表仅在 GNU/Linux 而不是 Windows 中导致段错误的更多相关文章

  1. ruby - 在 Ruby 程序执行时阻止 Windows 7 PC 进入休眠状态 - 2

    我需要在客户计算机上运行Ruby应用程序。通常需要几天才能完成(复制大备份文件)。问题是如果启用sleep,它会中断应用程序。否则,计算机将持续运行数周,直到我下次访问为止。有什么方法可以防止执行期间休眠并让Windows在执行后休眠吗?欢迎任何疯狂的想法;-) 最佳答案 Here建议使用SetThreadExecutionStateWinAPI函数,使应用程序能够通知系统它正在使用中,从而防止系统在应用程序运行时进入休眠状态或关闭显示。像这样的东西:require'Win32API'ES_AWAYMODE_REQUIRED=0x0

  2. ruby-on-rails - 如何优雅地重启 thin + nginx? - 2

    我的瘦服务器配置了nginx,我的ROR应用程序正在它们上运行。在我发布代码更新时运行thinrestart会给我的应用程序带来一些停机时间。我试图弄清楚如何优雅地重启正在运行的Thin实例,但找不到好的解决方案。有没有人能做到这一点? 最佳答案 #Restartjustthethinserverdescribedbythatconfigsudothin-C/etc/thin/mysite.ymlrestartNginx将继续运行并代理请求。如果您将Nginx设置为使用多个上游服务器,例如server{listen80;server

  3. ruby-on-rails - 使用 rails 4 设计而不更新用户 - 2

    我将应用程序升级到Rails4,一切正常。我可以登录并转到我的编辑页面。也更新了观点。使用标准View时,用户会更新。但是当我添加例如字段:name时,它​​不会在表单中更新。使用devise3.1.1和gem'protected_attributes'我需要在设备或数据库上运行某种更新命令吗?我也搜索过这个地方,找到了许多不同的解决方案,但没有一个会更新我的用户字段。我没有添加任何自定义字段。 最佳答案 如果您想允许额外的参数,您可以在ApplicationController中使用beforefilter,因为Rails4将参数

  4. ruby - 在 Windows 机器上使用 Ruby 进行开发是否会适得其反? - 2

    这似乎非常适得其反,因为太多的gem会在window上破裂。我一直在处理很多mysql和ruby​​-mysqlgem问题(gem本身发生段错误,一个名为UnixSocket的类显然在Windows机器上不能正常工作,等等)。我只是在浪费时间吗?我应该转向不同的脚本语言吗? 最佳答案 我在Windows上使用Ruby的经验很少,但是当我开始使用Ruby时,我是在Windows上,我的总体印象是它不是Windows原生系统。因此,在主要使用Windows多年之后,开始使用Ruby促使我切换回原来的系统Unix,这次是Linux。Rub

  5. ruby - 使用 `+=` 和 `send` 方法 - 2

    如何将send与+=一起使用?a=20;a.send"+=",10undefinedmethod`+='for20:Fixnuma=20;a+=10=>30 最佳答案 恐怕你不能。+=不是方法,而是语法糖。参见http://www.ruby-doc.org/docs/ProgrammingRuby/html/tut_expressions.html它说Incommonwithmanyotherlanguages,Rubyhasasyntacticshortcut:a=a+2maybewrittenasa+=2.你能做的最好的事情是:

  6. Vscode+Cmake配置并运行opencv环境(Windows和Ubuntu大同小异) - 2

    之前在培训新生的时候,windows环境下配置opencv环境一直教的都是网上主流的vsstudio配置属性表,但是这个似乎对新生来说难度略高(虽然个人觉得完全是他们自己的问题),加之暑假之后对cmake实在是爱不释手,且这样配置确实十分简单(其实都不需要配置),故斗胆妄言vscode下配置CV之法。其实极为简单,图比较多所以很长。如果你看此文还配不好,你应该思考一下是不是自己的问题。闲话少说,直接开始。0.CMkae简介有的人到大二了都不知道cmake是什么,我不说是谁。CMake是一个开源免费并且跨平台的构建工具,可以用简单的语句来描述所有平台的编译过程。它能够根据当前所在平台输出对应的m

  7. 【Java 面试合集】HashMap中为什么引入红黑树,而不是AVL树呢 - 2

    HashMap中为什么引入红黑树,而不是AVL树呢1.概述开始学习这个知识点之前我们需要知道,在JDK1.8以及之前,针对HashMap有什么不同。JDK1.7的时候,HashMap的底层实现是数组+链表JDK1.8的时候,HashMap的底层实现是数组+链表+红黑树我们要思考一个问题,为什么要从链表转为红黑树呢。首先先让我们了解下链表有什么不好???2.链表上述的截图其实就是链表的结构,我们来看下链表的增删改查的时间复杂度增:因为链表不是线性结构,所以每次添加的时候,只需要移动一个节点,所以可以理解为复杂度是N(1)删:算法时间复杂度跟增保持一致查:既然是非线性结构,所以查询某一个节点的时候

  8. 深度学习部署:Windows安装pycocotools报错解决方法 - 2

    深度学习部署:Windows安装pycocotools报错解决方法1.pycocotools库的简介2.pycocotools安装的坑3.解决办法更多Ai资讯:公主号AiCharm本系列是作者在跑一些深度学习实例时,遇到的各种各样的问题及解决办法,希望能够帮助到大家。ERROR:Commanderroredoutwithexitstatus1:'D:\Anaconda3\python.exe'-u-c'importsys,setuptools,tokenize;sys.argv[0]='"'"'C:\\Users\\46653\\AppData\\Local\\Temp\\pip-instal

  9. ruby - 如何计算 Liquid 中的变量 +1 - 2

    我对如何计算通过{%assignvar=0%}赋值的变量加一完全感到困惑。这应该是最简单的任务。到目前为止,这是我尝试过的:{%assignamount=0%}{%forvariantinproduct.variants%}{%assignamount=amount+1%}{%endfor%}Amount:{{amount}}结果总是0。也许我忽略了一些明显的东西。也许有更好的方法。我想要存档的只是获取运行的迭代次数。 最佳答案 因为{{incrementamount}}将输出您的变量值并且不会影响{%assign%}定义的变量,我

  10. ruby-on-rails - 只有当不是 nil 时才执行映射? - 2

    如果names为nil,则以下中断。我怎样才能让这个map只有在它不是nil时才执行?self.topics=names.split(",").mapdo|n|Topic.where(name:n.strip).first_or_create!end 最佳答案 其他几个选项:选项1(在其上执行map时检查split的结果):names_list=names.try(:split,",")self.topics=names_list.mapdo|n|Topic.where(name:n.strip).first_or_create!e

随机推荐