【问题标题】:Qt Segmentation Fault strtodQt 分段错误 strtod
【发布时间】:2016-07-03 08:18:19
【问题描述】:

每当我尝试从 C 字符串 (char *) 解析一个数字(即浮点数、双精度数等)时,都会遇到分段错误并且它非常一致。

进入实际代码:

//aLocation is a C++ object with two variables double Latitude & double Longitude. 
char** tokens; //Gets used in a string split function.
char* pEnd;
aLocation.setLatitude(strtod(tokens[0],&pEnd));  //tokens[0] = "26.379165"
aLocation.setLongitude(strtod(tokens[1],&pEnd)); //tokens[1] = "-80.101639"

应该提到的是,我已经尝试过替代函数和数据类型(即 atoi、atof、strtol、strtof 和 strtol)。

我检查了字符串拆分功能,它按预期工作。我可以使用“qDebug("Location: %s,%s",tokens[0],tokens1);" 很好地打印令牌值。两个段错误(一起或单独)上方的两个 strtod() 函数调用。当我从我的应用程序中删除上述两行代码时,我根本没有遇到任何 seq 错误。


运行环境是我使用 Buildroot 和旧版 Linux 内核 (3.4.39) 制作的自定义 Linux 映像。该应用程序是使用 Qt 4.8.4 SDK 用 C++ 编写的。我正在运行应用程序的设备是alix3d 主板,带有一些自定义 IC 添加(通过 USB)。我也在使用 ld-uClibc.so.0 库。

Location.h:

#ifndef LOCATION_H
#define LOCATION_H

class Location
{
public:
    explicit Location();
    void setLatitude(double aLat);
    double getLatitude();
    void setLongitude(double aLong);
    double getLongitude();


private:
    double latitude;
    double longitude;

};

#endif // LOCATION_H

Location.cpp:

#include "location.h"

Location::Location()
{
}

void Location::setLatitude(double aLat){latitude=aLat;}

double Location::getLatitude(){return latitude;}

void Location::setLongitude(double aLong){longitude = aLong;}

double Location::getLongitude(){return longitude;}

更新

Case 1: this->aLocation.setLatitude(1); ------> works (No additional code above or below)

Case 2:double aLat = (double)strtod(tokens[0], &pEnd); ---> works (No additional code below this)

Case 3: Below Code Seg faults 
double aLat = (double)strtod(tokens[0], &pEnd);
this->rsuLocation.setLatitude(aLat);

【问题讨论】:

  • 您可以尝试创建一个Minimal, Complete, and Verifiable Example 并展示给我们看吗?使用这么少(且不完整)的代码,实际上不可能说什么。例如,如果您单独执行 strtod 调用并且它们有效,那么您知道错误不在这些调用中,而是在其他地方。这样,您可以缩小创建 MCVE 的有问题的代码。您尝试在调试器中运行,以确定崩溃的位置?
  • 主要嫌疑人将是“字符串拆分函数”。
  • 字符串拆分功能就像一个魅力;我已经使用了一段时间了。我还通过打印输出来验证我的输出。在上面添加了更多信息。
  • 关于你的编辑,仅仅因为你可以打印一个字符串并且它看起来没问题,并不意味着它实际上是好的或正确的,或者指针是正确的。此外,即使您这样做,也会发生崩溃,例如double value = strtod(tokens[0], &pEnd); aLocation.setLatitude(value);?崩溃是否发生在strtod?那么错误是您的字符串或变量tokens(可能是指针问题)。如果崩溃发生在setLatitude,那么您继续查看那里。
  • 最后,这就是Minimal, Complete, and Verifiable Example 如此重要的原因。我们现在所做的只是猜测。使用MCVE,我们实际上可以看到所有相关代码,甚至希望自己尝试一下,我们不必猜测并且可以更快地给你一个直接的答案。此外,在创建MCVE 时,您有可能自己找出问题所在。

标签: c++ linux qt segmentation-fault


【解决方案1】:

我做了一个非常愚蠢的举动,忘记调用父对象的构造函数。

此外,我还更改了包含语句(即 #include )以及 QtCore 库目录(即 #include )。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-09-14
    • 1970-01-01
    • 1970-01-01
    • 2018-04-30
    • 1970-01-01
    • 2011-01-28
    • 2023-03-11
    • 2023-03-07
    相关资源
    最近更新 更多