Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why I am getting a segmentation fault while inserting elements to the vector of data inside the class?

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
like image 404
Anirban Saha Avatar asked Jul 17 '19 07:07

Anirban Saha


People also ask

How do I find out what is causing my 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.

What are three kinds of pointers that can cause a segmentation fault?

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).

What causes segmentation fault with pointers?

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.


1 Answers

Use std::vector::push_back().

Accessing the first element ( Set[0] ) is undefined behavior.

A default constructed vector is empty.

like image 87
AF_cpp Avatar answered Oct 07 '22 10:10

AF_cpp