2012-11-04 60 views
0
typedef struct { 
    double x; 
    double y; 
    long out_x; 
    long out_y; 
} coords; 

typedef struct { 
    char name[FIGURE_LEN + 1]; 
    int coordcount, size_tracker; 
    coords *coordinate; 
} fig; 

fig figure; 
fig * figpoint; 

這是從parser.c源文件中調用的函數。動態分配的結構數組中的SegFault,C

void initialize_fig(int n, char * name, double x, double y, 
         fig *fig_point) 
{ 
    printf("inside function\n"); 
    strncpy(fig_point[n].name, name, FIGURE_LEN + 1); 
    fig_point[n].size_tracker = 1; 
    fig_point[n].coordinate = malloc(sizeof(coords) * fig_point[n].size_tracker); 
    assert(fig_point[n].coordinate != NULL); 
    fig_point[n].coordcount = 0; 
    fig_point[n].coordinate[fig_point[n].coordcount].x = x; 
    fig_point[n].coordinate[fig_point[n].coordcount].y = y; 
} 

void create_FigArray(fig * fig_point, int fig_size) 
{ 
    fig_point = malloc(sizeof(fig) * fig_size); 
    assert(fig_point != NULL); 
    fig_point = &figure 
} 

我先打電話create_FigArray是這樣的...

create_FigArray(fig_point, 16); 

我沒有得到任何賽格故障這裏... 後來我打電話......

initialize_fig(0, Qe, 10.0000, 10.0000, fig_point); 

的參數實際上通過了變量,但我只是想表明它們是正確的參數,並給出了傳遞值的例子。 反正它擊中

strncpy(fig_point[n].name, name, FIGURE_LEN + 1); 

,並停止..段錯誤必須在這裏發生,但爲什麼?

請幫助,解釋並說明如何解決這個問題。謝謝。

+1

請您在回答後再編輯問題。這使得它很混亂。 – mathematician1975

回答

1

你分配內存,那麼你改變指針

fig_point = malloc(sizeof(fig) * fig_size); // allocate here 
assert(fig_point != NULL); 
fig_point = &figure; // now you make fig_point point to something else 

因此您fig_point指針不再指向您的動態分配的內存。如果你再這樣做

fig_point[n] 

您正在訪問內存不足或範圍,因爲figure不是一個數組。另外您直接將指針fig_point傳遞給create_FigArray。這將創建指針的副本,因此您對該參數所做的任何更改實際上只是對copy的更改。這意味着create_FigArray返回後fig_array中存儲的地址與以前的地址相同 - 它只是由函數更改的copy。如果你想改變指針,你需要使用雙指針函數參數,然後像

void create_FigArray(fig** fig_point, int fig_size) 
{ 
    *fig_point = malloc(sizeof(fig) * fig_size); 
} 
+0

是的 - 我得到相同的錯誤,沒有fig_point =&圖 – wenincode

+0

我編輯了代碼相同的錯誤 – wenincode

+0

@ user1787262沒有不編輯問題!這讓任何試圖回答你問題的人都感到困惑。 – mathematician1975

1

我不知道,但:

首先,你分配內存fig_point:

fig_point = malloc(sizeof(fig) * fig_size); 

然後你分配圖的地址,你不應該這樣做。

fig_point = &figure; 

你可以這樣做,而不是:

figure = *fig_point; 
+0

我編輯了代碼相同的錯誤 – wenincode

+0

你不能分配圖的地址到你分配的fig_point。 – fonZ

+0

身材不是指針! – askmish

1
  • create_FigArray你這樣做:fig_point =的malloc(的sizeof(圖)* fig_size);然後這樣的: fig_point = &figure; //figure is a global variable and this causes a memory leak

  • 而是寫:

void create_FigArray(fig * fig_point, int fig_size) 
{ 
    fig_point = malloc(sizeof(fig) * fig_size); 
    assert(fig_point != NULL); 
    fig_point = &figure;//Remove this line 
} 
  • 在從正在調用initialize_fig()或某個功能,確保以釋放分配的內存。

  • 在使用之前使所有指針爲NULL,並在處理指針的函數中添加NULL參數檢查,並在使用前檢查NULL指針。