-4

I am trying to solve a CodeChef problem. Whenever I run it I get a segmentation fault. This is the link to the problem: Malvika is peculiar about color of balloons

Here is my code :

#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;
    }
}
Sriram Kailasam
  • 347
  • 3
  • 13
  • 1
    You use the debugger and step through your program line by line, until the segfault occurs. Then check all of your variables values at this point. – πάντα ῥεῖ Apr 23 '16 at 05:21

2 Answers2

0

These lines is the problem:

int t;
int results[t];

You declare results using the uninitialized variable t. An uninitialized variable have an indeterminate value, and using it before initialization leads to undefined behavior.

You should use a std::vector here, and set its size once you get the actual size from the user:

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

std::cin >> t;

results.resize(t);
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
0

Arrays in C++ need to have a fixed size. You defined results with size t, which isn't fixed.

To use dynamic size, use a std::vector instead:

#include <vector>
...
int t;
std::cin >> t;
std::vector<int> results (t);
CinCout
  • 9,486
  • 12
  • 49
  • 67