Below are my codes...
main.cpp
/* header files are included here */
PCI_card card;
int main(void)
{
card.init_card(0);
return 0;
}
pci_card.h
#ifndef __PCI_CARD_H
#define __PCI_CARD_H
/* header files are included here */
typedef struct {
int32_t card_index;
int32_t user_counter;
} card_dev_t;
class PCI_card {
public:
PCI_card() : dev_descriptor(-1) { enlarge_vector(); }
int32_t init_card(int32_t card_num);
private:
int32_t dev_descriptor;
public:
static int32_t enlarge_vector();
private:
static int32_t card_amount;
static std::vector<card_dev_t> cards;
};
#endif
pci_card.cpp
/* header files are included here */
int32_t PCI_card::card_amount = -1;
std::vector<card_dev_t> PCI_card::cards;
int32_t PCI_card::init_card(int32_t card_num)
{
if (card_num >= card_amount || card_num < 0)
return -1;
card_dev_t new_card = {
.card_index = card_num,
.user_counter = 1
};
cards[card_num] = new_card;
dev_descriptor = card_num;
return 0;
}
int32_t PCI_card::enlarge_vector()
{
card_amount = 10;
card_dev_t null_card = {
.card_index = -1,
.user_counter = -1
};
cards.resize(card_amount, null_card);
return card_amount;
}
In main.cpp, card
is defined as a global variable, and of course, it should be initialized before invoking main()
function, and this can be seen clearly via gdb.
When initializing card
, constructor of class PCI_card
is invoked, the vector cards
in this class is resized according to card_amount
member variable. From the gdb, this vector does be initialized properly, it contains 10 elements.
Weird things happened before invoking main()
function, the vector is reset. In gdb, the size of vector rolled back to 0, and of course, subsequent operations, such as subscript this vector, cause segment fault error.
I don't know what happen here.... it is too ridiculous...