【问题标题】:Deal with segmentation fault [closed]处理分段错误[关闭]
【发布时间】:2016-04-23 05:18:48
【问题描述】:

我正在尝试解决 CodeChef 问题。每当我运行它时,我都会遇到分段错误。这是问题的链接:Malvika is peculiar about color of balloons

这是我的代码:

#include<iostream>
#include<cstring>
#include<algorithm>

int main(){
    std::string balloonColors;
    size_t numberOfAmber;
    size_t numberOfBrass;
    int t;
    int results[t];

    std::cin >> t;

    for (int i = 0; i < t; i++){
        int result = 0;
        std::cin >> balloonColors;
        numberOfAmber = std::count(balloonColors.begin(), balloonColors.end(), 'a');
        numberOfBrass = std::count(balloonColors.begin(), balloonColors.end(), 'b');

        if (numberOfAmber == 0 || numberOfBrass == 0){
            result = 0;
        }

        if (numberOfAmber <= numberOfBrass){
            result = (int)numberOfAmber;
        }
        else {
            result = (int)numberOfBrass;    
        }

        results[i] = result;

    }
    for (int x = 0; x < t; x++){
        std::cout << results[x] << std::endl;
    }
}

【问题讨论】:

  • 您使用调试器并逐行执行程序,直到发生段错误。然后此时检查所有变量值。

标签: c++ segmentation-fault


【解决方案1】:

这几行是问题所在:

int t;
int results[t];

您使用未初始化变量t声明results。未初始化的变量有一个 indeterminate 值,在初始化之前使用它会导致 未定义的行为

您应该在此处使用std::vector,并在从用户那里获得实际大小后设置其大小:

int t;
std::vector<int> results;

std::cin >> t;

results.resize(t);

【讨论】:

  • 啊,我明白了。非常感谢!
【解决方案2】:

C++ 中的数组需要有固定的大小。您使用大小t 定义了results,这不是固定的。

要使用动态大小,请改用std::vector

#include <vector>
...
int t;
std::cin >> t;
std::vector<int> results (t);

【讨论】:

    猜你喜欢
    • 2020-06-15
    • 1970-01-01
    • 1970-01-01
    • 2018-09-13
    • 2018-10-08
    • 1970-01-01
    • 2016-01-11
    • 2018-11-18
    相关资源
    最近更新 更多