运行 在 C++ 中尝试将字符串转换为双精度时出现段错误

Running Into Segmentation Fault When Attempting To Convert String To Double in C++

我正在开发一个相当简单的优先级调度程序,该程序采用格式为行的文本文件:

[N/S/n/s] number number

我正在尝试将数字转换为双精度格式。我正在尝试使用 stringstream(这是一个 class 项目,必须 运行 在没有 stod 的 Linux 版本上执行此操作),使用此处的示例作为参考:https://www.geeksforgeeks.org/converting-strings-numbers-cc/

问题是,当我尝试实现我认为应该是相当简单的几行代码时,我遇到了 "Segmentation Fault (Core Dumped)",这似乎与我的尝试直接相关实际上将 stringstream 发送到我创建的 double 变量。到目前为止,我已经包含了我的代码(显然还远未完成)并且还指出了我能够通过输出执行的最后一行 "made it to here." 我对这个问题很困惑,非常感谢任何帮助可用的。请注意,虽然我为了完成而发布了我的整个代码,但只有靠近底部的一小部分与我已经明确指出的问题相关。

代码:

#include <iostream>
#include <stdio.h>
#include<string.h>
#include <stdlib.h>
#include<cstring>
#include<sstream>
#include<cstdlib>
#include <unistd.h>
#include<pthread.h>
#include<ctype.h>
#include <vector>
#include <sys/wait.h>
#include <fstream>
#include<ctype.h>
using namespace std;

struct Train{
        public:
        char trainDirection;
        double trainPriority;
        double trainTimeToLoad;
        double trainTimeToCross;
};

void *trainFunction (void* t){cout << "placeholder function for "<< t <<endl;}

vector<string> split(string str, char c = ' '){

        vector<string> result;
        int start = 0;
        int end = 3;
        int loadCounter = 1;
        int crossCounter = 1;

        result.push_back(str.substr(start, 1));
        start = 2;

        while (str.at(end) != ' '){
                end++;
                loadCounter++;
        }

        result.push_back(str.substr(start, loadCounter));

        start = end + 1;
        end = start +1;

        while(end < str.size()){
                end++;
                crossCounter++;
        }

        result.push_back(str.substr(start, crossCounter));

        for(int i = 0; i < result.size(); i++){
                cout << result[i] <<"|";
        }

        cout<<endl;
        return result;
}

int main(int argc, char **argv){
//READ THE FILE

        const char* file = argv[1];
        cout << file <<endl;
        ifstream fileInput (file);
        string line;
        char* tokenPointer;
        int threadCount = 0;
        int indexOfThread = 0;

        while(getline(fileInput, line)){
                threadCount++;
        }

        fileInput.clear();
        fileInput.seekg(0, ios::beg);

//CREATE THREADS

        pthread_t thread[threadCount];

        while(getline(fileInput, line)){

                vector<string> splitLine = split(line);

                //create thread

                struct Train *trainInstance;

                stringstream directionStringStream(splitLine[0]);
                char directionChar = 'x';
                directionStringStream >> directionChar;
                trainInstance->trainDirection = directionChar;

                if(splitLine[0] == "N" || splitLine[0] == "S"){
                        trainInstance->trainPriority = 1;
                }
                else{
                        trainInstance->trainPriority = 0;
                }

                stringstream loadingTimeStringStream(splitLine[1]);
                double doubleLT = 0;
                cout << "made it to here" <<endl;
                loadingTimeStringStream >> doubleLT;        //THIS IS THE PROBLEM LINE
                trainInstance->trainTimeToLoad = doubleLT;

                stringstream crossingTimeStringStream(splitLine[2]);
                double doubleCT = 0;
                crossingTimeStringStream >> doubleCT;
                trainInstance->trainTimeToCross = doubleCT;

                pthread_create(&thread[indexOfThread], NULL, trainFunction,(void *) trainInstance);

                indexOfThread++;
        }
}

您通过 -> 运算符取消引用 trainInstance,但未分配有效缓冲区,因此系统将尝试写入奇怪的地方并导致分段错误。

您可以这样分配缓冲区:

struct Train *trainInstance = new struct Train;

struct这里不需要,但是我用了一个,因为原代码中用到了

在使用 argv[1] 之前不要忘记检查参数的数量。

您的代码中存在一些导致未定义行为的错误,这就是您的分段错误的原因。即:

  • 你在使用前没有检查参数的数量

  • 您没有 return trainFunction

  • 中的值
  • 您没有为 trainInstance 创建指向

  • 的有效对象

前两个比较容易解决,那我就说最后一个吧。 C++ 中的内存管理是微妙的,正确的解决方案取决于您的用例。因为 Train 对象很小,所以最好将它们分配为局部变量。这里棘手的部分是确保它们不会过早销毁。

简单地将声明更改为 struct Train trainInstance; 是行不通的,因为该结构将在当前循环迭代结束时被销毁,而线程仍可能处于活动状态并尝试访问该结构。

为了确保 Train 对象在线程完成后被销毁,我们必须在线程数组之前声明它们,并确保在线程超出范围之前加入线程。

Train trainInstances[threadCount];
pthread_t thread[threadCount];

while(...) {
    ...
    pthread_create(&thread[indexOfThread], nullptr, trainFunction,static_cast<void *>(&trainInstances[indexOfThread]));
}
// Join threads eventually

// Use trainInstances safely after all threads have joined

// trainInstances will be destroyed at the end of this scope

这很干净并且可以工作,但它不是最佳的,因为出于某种原因您可能希望线程比 trainInstances 更长寿。在这种情况下,让它们保持活动状态直到线程被销毁是一种内存浪费。根据对象的数量,甚至可能不值得浪费时间来优化它们的销毁时间,但您可以执行以下操作。

pthread_t thread[threadCount];
{
    Train trainInstances[threadCount];
    while(...) {
        ...
        pthread_create(&thread[indexOfThread], nullptr, trainFunction,static_cast<void *>(&trainInstances[indexOfThread]));
    }
    // Have threads use some signalling mechanism to signify they are done
    // and will never attempt to use their Train instance again

    // Use trainInstances

 }  // trainInstances destroyed

    // threads still alive

在处理不提供 C++ 接口的线程时最好避免使用指针,因为当您不能简单地按值传递智能指针时,处理动态内存管理会很痛苦。如果您使用 new 语句,执行必须始终准确地到达 returned 指针上对应的 delete 语句。虽然这在某些情况下听起来微不足道,但由于潜在的例外情况和早期的 return 语句而变得复杂。

最后,请注意 pthread_create 调用对以下内容的更改。

pthread_create(&thread[indexOfThread], nullptr, trainFunction,static_cast<void *>(&trainInstances[indexOfThread]));

这条线路的安全性有两个重大变化。

nullptr 的使用:NULL 具有整数类型,可以静默传递给 non-pointer 参数。如果没有命名参数,这是一个问题,因为如果不查找函数签名和验证参数 one-by-one 就很难发现错误。 nullptr 是 type-safe 并且在没有显式转换的情况下将其分配给 non-pointer 类型时将导致编译器错误。

static_cast 的使用:C-style 转换是危险的事情。他们会尝试一系列不同的演员表,然后选择第一个有效的演员表,这可能不是您想要的。看看下面的代码。

// Has the generic interface required by pthreads
void* pthreadFunc(void*);

int main() {
    int i;
    pthreadFunc((void*)i);
}

糟糕!本来应该是(void*)(&i)i的地址转成void*。但是编译器不会抛出错误,因为它可以将整数值隐式转换为 void*,因此它只会将 i 的值转换为 void* 并将其传递给函数潜在的灾难性影响。使用 static_cast 将捕获该错误。 static_cast<void*>(i) 根本无法编译,所以我们注意到我们的错误并将其更改为 static_cast<void*>(&i)