初始化存储结构体指针时触发Segmentation Fault的原因排查
C语言代码中Segmentation Fault的排查
我编写了以下C语言代码,尝试将market_order结构体存入products.buys数组中,但在products->buys[products->buy_levels] = new_order;这一行触发了Segmentation Fault,请问可能的原因是什么?
结构体定义
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;
初始化与添加订单的代码
在main函数中,为全局products指针初始化内存:
products = malloc(sizeof(struct products));
用于向products.buys添加新元素的函数:
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; }
可能的原因
- 全局指针
products未完成初始化就被访问:products是全局指针,默认初始值为NULL。如果populate_buy_orders在main里的malloc调用之前被执行,此时访问products->buy_levels或products->buys会直接触发段错误。 buy_levels初始值非法导致数组越界:通过malloc分配的products结构体,其成员buy_levels未被显式初始化,堆内存的初始值是随机垃圾值。如果这个随机值大于等于20(buys数组的长度),直接访问products->buys[products->buy_levels]会越界访问非法内存,引发段错误。即使初始值合法,当添加的订单数量超过20时,同样会触发越界问题。products的内存分配失败未被检查:malloc可能因内存不足返回NULL,如果没有检查这个返回值,后续访问products的成员会通过空指针触发段错误。
内容的提问来源于stack exchange,提问作者HyperCoderSuperion
相关产品推荐
相关产品推荐

