(c++) How could I fix a segmentation fault from a function built to print vector elements?

I’m pretty new to programming more seriously and was confused as to what a segmentation fault is. I was trying to build a function that would draw a map of “stars” for a game I was making.

#include <iostream>
#include <string>
#include <vector>
#include <cstdlib>



void map_generator() {
    srand(time(NULL));
    std::vector<std::string> map_chunks;
    std::vector<std::string> star_patterns = { "*    ", " *   ", "  *  ", "   * ", "    *", "     " };

    while (map_chunks.size() < 60) {

        for (int i = 0; i <= map_chunks.size(); i++) {

            if (i % 6 != 0) {

                for (int k = 0; k < star_patterns.size(); k++) {

                    map_chunks.push_back(star_patterns[std::rand() % 6]);



                }


            }
            else {
                map_chunks[i] = "\n";
            }


        }


    }

 
} 

The map was supposed to be 25 characters long and 10 rows tall, and so I created a vector with 6 different possibilities for potential patterns with combinations of spaces and an asterisk that were supposed to be put into another vector that was going to display. Each sixth element of the vector would be changed to a line break to make more rows. In order to test if the variable map_chunks was actually storing anything, I printed map_chunks[5] at the bottom of the function. In the end I want the entire thing to print (which I’m also trying to figure out) but when I call this in main and then compile and execute the program it says “segmentation fault.” And I’m not sure what it means by this.

If you have a web search for segmentation faults you’'ll find plenty of background. One of the easy ways to get it though is to try and access elements outside the array. Make sure your array is large enough for your indexing wherever you use indexing, I’d hazard a guess at map_chunks[i] being a potential problem but a few output statements and some basic debugging is the right way to go.

1 Like

Thank you very much, removing the map_chunks[i] made the segmentation fault go away. I’m gonna have to do some more research on what exactly segmentation faults are and how they work.

Also, would you happen to know if there’s a way to print out all of the contents of a vector? That’s the big funcitonality part of this program that I can’t quite get. I try using for loops to iterate through it and print out each element but it never seems to work.

There would be several ways to do it but using a range based for loop- Range-based for loop (since C++11) - cppreference.com might be an easy option since you don’t have to try and index or check the size yourself.

std::vector<int> values(3, 0);
for (auto val: values)
    std::cout << val << ' ';
1 Like

This topic was automatically closed 41 days after the last reply. New replies are no longer allowed.