I am receiving segmentation fault while inserting data inside the vector. I think the vector is not allocated.
I do not want to reserve
size. How to do it?
class A
{
private:
struct data
{
int x;
int y;
};
std::vector<data>Set;
public:
void insert()
{
Set[0].x = 5; Set[0].y = 6;
}
};
A a;
a.insert(); // Segmentation Fault
Use debuggers to diagnose segfaults Start your debugger with the command gdb core , and then use the backtrace command to see where the program was when it crashed. This simple trick will allow you to focus on that part of the code.
Causes of segmentation fault:Attempting to access a nonexistent memory address (outside process's address space). Attempting to access memory the program does not have rights to (such as kernel structures in process context). Attempting to write read-only memory (such as code segment).
A segmentation fault usually occurs when you try to access data via pointers for which no memory has been allocated. It is thus good practice to initialize pointers with the value NULL, and set it back to NULL after the memory has been released.
Use
std::vector::push_back()
.
Accessing the first element ( Set[0]
) is undefined behavior.
A default constructed vector is empty.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With