HELP! Getting a segmentation fault with this paRT OF MY CODE

Write your question here.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
template <typename T>
void Library<T>::generate()
{
   std::string author_names[] = {"James Wilson", "Thomas George", "Peter Lammens", "Matthew Marker" };
   
   std::vector<std::vector<std::string> > all_books = {
      {"Ready Ribbons", "Jumping Down", "Living In Life"},
      {"Just Shaved", "Ordering Dogs", "Partly Done"},
      {"Move Allowed", "No Way, No Play", "Kick Up"}
   };

   // Sets the books for each author.
   for (int i = 0; i < 3; ++i)
   {
      authors.push_back(Author<std::string>(author_names[i]));
      for (int i = 0; i < 3; ++i)
      {
         authors[i].set_book(all_books[i][j]);
      }
   }
}
You probably meant to use j, not i, as the control index in the inner loop!
If that compiles (as a segfault would imply), it means you have a global variable with the name 'j'.
I would nuke that code from orbit, personally.

Edit: Actually, it could just be a class-scope variable with the name 'j'. Still, really poor name for anything but a loop variable.
Last edited on
all_books has a size 3 x 3 NOT 4 x 3 - hence seg fault when trying to access [3] as the last element is [2].

As you haven't provided working code that will compile, have a look at this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#include <string>
#include <vector>
#include <iostream>

struct Author {
	std::string name;
	std::vector<std::string> books;

	Author(std::string n) : name(std::move(n)) {}

	void set_book(std::string book) {
		books.emplace_back(std::move(book));
	}

};

struct Library {
	void generate();
	std::vector<Author> authors;
};

void Library::generate() {
	const static std::string author_names[] { "James Wilson", "Thomas George", "Peter Lammens", "Matthew Marker" };

	const static std::vector<std::vector<std::string> > all_books {
	   {"Ready Ribbons", "Jumping Down", "Living In Life"}, // James Wilson
	   {"Just Shaved", "Ordering Dogs", "Partly Done"},  // Thomas George
	   {"Move Allowed", "No Way, No Play", "Kick Up"} // Peter Lammens
	   // No books for Matthew Marker!
	};

	// Sets the books for each author.
	authors.clear();
	for (size_t cnt {}; const auto& a : author_names)
		if (authors.emplace_back(a); cnt < all_books.size())
			for (const auto& b : all_books[cnt++])
				authors.back().set_book(b);
}

int main() {
	Library lib;

	lib.generate();

	for (const auto& l : lib.authors) {
		std::cout << l.name << '\n';

		for (const auto& b : l.books)
			std::cout << b << '\n';

		std::cout << '\n';
	}
}


which displays:


James Wilson
Ready Ribbons
Jumping Down
Living In Life

Thomas George
Just Shaved
Ordering Dogs
Partly Done

Peter Lammens
Move Allowed
No Way, No Play
Kick Up

Matthew Marker

Last edited on
Thank you everyone
Topic archived. No new replies allowed.