英文:
Segmentation Fault when trying to intialize to store pointer to a struct
问题
我尝试将market_order结构体存储到我的products.buys数组中,但在这一行出现了分段错误:products->buys[products->buy_levels] = new_order;可能的问题是什么?
英文:
I have the following code, I am trying to store a market_order struct into my products.buys array
Here are what my structs look like
typedef struct market_order {
char type[5];
int price;
int quantity;
char item[20];
int traderId;
int orderId;
int number_of_orders;
int orderCount;
} MarketOrder;
typedef struct products{
int buy_levels;
int sell_levels;
struct market_order *buys[20];
struct market_order *sells[20];
} Products;
struct products *products;
In my main method, in initalize memory space for my global products ptr.
Like this
products = malloc(sizeof(struct products));
I then have another method that adds new elements to my products.buys keeping a counter for how many elements I have added so iteration is easier.
void populate_buy_orders(int traderId, int orderId, char* item, int quantity, int price){
MarketOrder* new_order = malloc(sizeof(struct market_order));
if (new_order == NULL) {
printf("Failed to allocate memory for new order\n");
return;
}
new_order->traderId = traderId;
new_order->orderId = orderId;
new_order->quantity = quantity;
new_order->price = price;
new_order->number_of_orders = 1;
new_order->orderCount = products->buy_levels;
products->buys[products->buy_levels] = new_order;
++products->buy_levels;
}
I get a segmentation fault at this line
products->buys[products->buy_levels] = new_order;
What could be the issue?
答案1
得分: 2
malloc
函数仅分配指定数量的内存,不进行初始化。因此,在分配后,您的products->buy_levels
成员包含一些随机值。当您将此值用作数组索引时,它超出界限,导致段错误。您应该在分配后要么使用默认值初始化结构,要么使用calloc
以便对分配的缓冲区进行默认零初始化。
英文:
malloc
function only allocates specified amount of memory, it does not initialize it. So after allocating, your products->buy_levels
member contains some random value. When you use this value as array index, it goes over the bounds and you get a segfault. You should either initialize your struct with default values after allocating, or use calloc
instead for the default zero-initialization of the allocated buffer.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论