0

I have two structs ITEM and TABLE, one of which contains the other one, i.e. TABLE contains many ITEMS. I use this code to create the structs and the table and items with it.

#include <iostream>
#include <string>
#include <sstream>
#include <vector>

struct ITEM {
 std::string itemTitle;
};

struct TABLE {
 std::string tableName;
 int num;
 ITEM* items;
};

TABLE setTABLE(std::string, int num) {
 struct ITEM* item = (struct ITEM*) malloc(sizeof(struct ITEM) * num);
 TABLE table = {tableName, num, item};
 return table;
}

int main() {
 std::vector<TABLE> tables;
 tables.push_back(setTABLE("TEST", 3));
 tables[0].items[0].itemTitle = "TestItem";
 std::cout << tables[0].items[0].itemTitle << "\n";

 return 0;
}

I want to set the itemTitle of the ITEM at position 0, but when I cout the result i get

Segmentation fault: 11

I guess the malloc is not sufficient to this? Or is my code construction misconstrued in the first place? What I wanted to achieve is build a custom table structure.

2 Answers 2

2

malloc() allocates memory, whereas new allocates memory and initializes (invoking a constructor of an object for example). As malloc() is being used items is a pointer to allocated but uninitialized memory which is accessed at:

tables[0].items[0].itemTitle = "TestItem";

causing the segmentation fault. But, don't use new just use a std::vector<ITEM> instead. An initial size is not required but can be supplied if required and the vector constructed with n default elements:

struct Table
{
    Table(std::string const& aName, const size_t a_num) :
        tableName(aName), items(a_num) {}
    std::string tableName;
    std::vector<Item> items;
};

Note num no longer required as items.size() can be used and don't use all uppercase as these are generally used for macros.

Sign up to request clarification or add additional context in comments.

Comments

0

you are returning variable table which is created on the stack -- you will need to malloc memory for table first

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.