c++ - 意外溢出 C++(特定于 Windows)

标签 c++ windows macos

我似乎遇到了意外溢出,我不明白为什么会发生这种情况(令我非常沮丧):

Windows :

enter image description here

麦克:

enter image description here

这些都是使用 MinGW 编译的。我认为这可能是由于 BSD 和 Windows 之间的文件类型不同,因为我注意到如果我从 Windows 操作系统复制 numbers.txt,我会收到类似的错误。

Windows 文件的 Mac 错误:

Mac Shell: Downloads/>$ rm numbers.txt 
# Downloaded new numbers.txt file from windows.
Mac Shell: Downloads/>$ ./Project1 

Raw output:
-----------
Segmentation fault: 11
Mac Shell: Downloads/>$

Windows 和 Mac 文件:

enter image description here

代码:

void do_file_magic(string file){
    string line, replace = "", numeral, dump = "", temp;
    ifstream source ("numbers.txt");
    if (!source.is_open()) {
        die_a_clean_death("Unable to open source file:", file);
    };

    // Display output to console:
    sep("Raw output:");

    // read source file and output vowels to destination file.
    while ( getline(source, line) || true) {
        dump = dump + replace;
        if ( line[0] != ' ') {
            temp = num2string(roman2num(line));
            line = remove_whitespace(line);
            replace = line + string(17-line.size(), ' ') + temp + "\n";

        // If you read this then you noticed that there was some shenagins going on.
        } else {
            numeral = num2roman(string2num(line));
            line = remove_whitespace(line);
            replace = numeral + string(17 - numeral.size(), ' ') + line + "\n";
        };
        if(source.eof()) {
            break;
        }
    };
    printf("file dump: \n%s", dump.c_str());


    // Close the files
    source.close();

    // open the file in output mode nuking everything from orbit.
    // (Its the only way to be sure)
    ofstream destination("numbers.txt");
    if (!destination.is_open()) {
        die_a_clean_death("Unable to open destination file:", file);
    };

    // Just dump a variable to the file.
    destination << dump << "\n";

    destination.close();
};

有人可以帮助我了解我哪里出错了吗?

最佳答案

可能还有更多问题,但我发现的第一个是:

while ( getline(source, line) || true) {
    ...
    if ( line[0] != ' ') ...

如果调用getline失败,line将是空的,所以 line[0]出界了。

关于c++ - 意外溢出 C++(特定于 Windows),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39753615/

相关文章:

c++ - 如何调试多线程 C++ 程序的哪个部分花费了过多的时间?

.net - VB 中有 "coroutine"功能吗?

macos - Quartz Composter —重新创建Audioskop(根据音频输入调整视频时间)

c# - 更好地处理丢失的 .NET Framework (0xc0000135) 崩溃?

c++ - 在 Linux 中使用 PE 节头

macos - Sublime Text 3 侧边栏文件和文件夹卡住或不显示

android - ionic 构建 android,错误 : spawn EACCES

c++ - 用户输入无效

c++ - 读取变量作为执行时的参数

C++虚赋值运算符