Slugger Slugger - 4 months ago 24
C++ Question

Segmentation fault during counting of elements in array of strings c++

I am trying to solve an old problem found on topcoder. I am immediately stuck in trying to find the number of elements in an array of strings. Here is my code

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string>

using namespace std;

class MiniPaint {
size_t numLines;

int leastBad(string picture[], int maxStrokes) {
numLines = 0;
while (!picture[numLines].empty()) {

cout << numLines << '\n';

return 0;


int main() {

MiniPaint instance;

instance.leastBad(picture, 10);
return 0;

This code gives me a segmentation fault. Something is going wrong, the code is a little bit excessive for just the functionality of counting the number of elements but of course I want to extend the class to include more functionality. If anyone can explain what is going wrong here I would be grateful! Thanks in advance.

EDIT: when I expand the code by

cout << picture[numlines] << '\n';

in the while loop, to show the actual elements in the array, first the four proper strings are shown and then somehow it endlessly prints spaces to the terminal. So the problem lies somewhere in the fact that


does not return true, even though picture has only four elements.


Your while loop condition assumes that the last string in the array is empty:

int leastBad(string picture[], int maxStrokes) {
    numLines = 0;
    while (!picture[numLines].empty()) {

But your input string array defined in main() is not terminated with an empty "" string.

So you may want to add this empty string terminator:

// inside main()

string picture[] = {..., "" /* Empty string terminator */ };

In addition, in modern C++ I'd encourage you to use array container classes instead of raw C-style arrays, typically std::vector<std::string>.

In this case, you can use the size() method to get the array size (i.e. element count), or just a range-for loop for iterating through the whole array.