[英]Array of undefined length of structures generates segmentation fault
我正在編寫一個編譯器項目。 我創建了一個AST樹,其中每個節點都由結構定義:
typedef struct node {
char type[10];
char *string;
int number_of_children;
struct node *children[];
} node;
我想創建一個未定義長度的符號數組。 我創建了結構,以存儲符號的名稱及其在內存中的地址:
typedef struct symbol {
char *name;
int address;
} symbol;
然后我創建了未定義長度的數組:
symbol *symbols_table[];
我創建了添加新符號的函數:
void add_symbol(node *p) {
symbols_table[number_of_symbols] = malloc(sizeof(symbol));
symbols_table[number_of_symbols]->name = malloc(sizeof(p->string));
strcpy(symbols_table[number_of_symbols]->name, p->string);
symbols_table[number_of_symbols]->address = memory_pointer;
memory_pointer++;
number_of_symbols++;
}
其中p
是來自AST樹的節點,需要memory_pointer
來為每個符號提供內存中的地址。
這就是問題所在。 當我想在symbols_table
只添加2個符號時,一切正常。 但是當我想要添加3個或更多時,它會給出segmentation fault
。 你有什么想法,為什么會這樣?
我在這里看到的問題是
symbols_table[number_of_symbols]->name = malloc(sizeof(p->string));
在你的代碼中, string
是一個指針。 因此, sizeof(p->string))
不會給你分配內存的大小,它會給你指針本身的大小。 稍后,當你執行strcpy()
它會超出分配的內存,從而產生未定義的行為 。
你想要的是
symbols_table[number_of_symbols]->name = malloc(strlen(p->string) + 1);
獲得適當的內存分配。
在不同的方法中,您還可以查看strdup()
以避免整個malloc()
+ strcpy()
事情。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.