【问题标题】:c++ stringstream conversion error: segmentation faultc++ stringstream转换错误:分段错误
【发布时间】:2013-02-19 15:47:52
【问题描述】:

我在尝试将整数转换为字符串的简单函数时遇到了一些问题。代码如下:

string Problem::indexB(int i, int j, int k){    
    stringstream ss;

    if(i < 10)
        ss << "00";
    else if(i<100)
        ss << "0";
    ss << i;

    if(j < 10)
        ss << "00";
    else if(j<100)
        ss << "0";
    ss << j;

    if(k < 10)
        ss << "00";
    else if(k<100)
        ss << "0";
    ss << k;

    return ss.str();
}

该函数工作正常,但是当进行多次调用时,它会在某些时候给我一个分段错误。

【问题讨论】:

  • 哪一点?你做了什么来调试它?
  • 错误不在此代码片段中。尝试使用 valgrind 定位堆栈损坏或类似情况
  • 问题出在退货线路上。在我多次调用该函数后,“.str()”将导致分段错误。这是 gdb Program received signal SIGSEGV, Segmentation fault. _int_malloc (av=0x7ffff74191c0, bytes=26) at malloc.c:4339 4339 malloc.c: File or directory not found. in malloc.c 的相关问题

标签: c++ string stringstream


【解决方案1】:

对我来说很好用:http://ideone.com/lNOfFZ

完整的工作程序:

#include <string>
#include <sstream>
#include <iostream>

using std::string;
using std::stringstream;

class Problem {
public:
    static string indexB(int i, int j, int k);
};

string Problem::indexB(int i, int j, int k){

    stringstream ss;

    if(i < 10)
        ss << "00";
    else if(i<100)
        ss << "0";
    ss << i;

    if(j < 10)
        ss << "00";
    else if(j<100)
        ss << "0";
    ss << j;

    if(k < 10)
        ss << "00";
    else if(k<100)
        ss << "0";
    ss << k;

    return ss.str();
}

int main() {
    std::cout << Problem::indexB(1, 2, 3) << "\n";
    std::cout << Problem::indexB(400, 50, 6) << "\n";
    std::cout << Problem::indexB(987, 65, 432) << std::endl;
}

分段错误通常发生在程序遇到未定义行为之后的一段时间,因此检测到错误时的堆栈跟踪不一定与错误代码在同一个函数中。

【讨论】:

  • gdb相关的问题在“.str()”函数中。这是我从调试器中得到的Program received signal SIGSEGV, Segmentation fault. _int_malloc (av=0x7ffff74191c0, bytes=26) at malloc.c:4339 4339 malloc.c: File or directory not found. in malloc.c
  • 找到了!问题是我将结果存储在向量中。经过一些电话,我正在清除矢量并且不再调整它的大小。问题不在于返回,而在于用于存储结果的变量。谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-10-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-01
  • 1970-01-01
相关资源
最近更新 更多