2012-03-02 98 views
0

我正在C中實現一些多項式算術。我使用動態結構來存儲整數因子和多項式次數。 除了其他函數我需要操作p [X] * X,所以我試圖實現某種右移。realloc()在重複調用後失敗

但經過幾個班次realloc()崩潰我的程序。在這個例子中,它是在第三次調用,但如果我嘗試移動2次和4次,它會在第二次後崩潰。

/* Simple polynom type with variable length and degree n-1. */ 
typedef struct { 
    int n; 
    int *factors; 
} polynom_t; 


polynom_t *poly_init(int n) { 
    polynom_t *p_new = malloc(sizeof(polynom_t)); 
    p_new->n = n; 
    p_new->factors = calloc(n, sizeof(int)); 

    return p_new; 
} 

void poly_clear(polynom_t *p) { 
    free(p->factors); 
    free(p); 
    p = NULL; 
} 


void poly_set(polynom_t *p, int a[], int len){ 
    memcpy(p->factors, a, sizeof(int)*p->n); 
} 


void _poly_rsz(polynom_t *p, int n) { 
    if (n != p->n) { 
     p->n = n; 

     // This realloc() seems to fail 
     p->factors = realloc(p->factors, sizeof(int) * n); 
    } 
} 


void _poly_lsr(polynom_t *p, int i) { 
    _poly_rsz(p, p->n + i); 
    memmove(p->factors + i, p->factors, sizeof(int)*(p->n)); 
    memset(p->factors, 0, sizeof(int)*i); 
} 


int main(int argc, char **argv) { 
    polynom_t *p2 = poly_init(11); 
    int a2[11] = {1, 2, 0, 2, 2, 1, 0, 2, 1, 2, 0}; 
    poly_set(p2, a2, 11); 
    _poly_lsr(p2, 1); // works as expected 
    _poly_lsr(p2, 1); // works as expected 
    _poly_lsr(p2, 1); // crash 
    poly_clear(p2); 

    return 0; 
} 
+0

奇。當我運行這個代碼瓦特/ gcc時,我得到這個錯誤:對象0x6868cf0的***錯誤:對於釋放的對象不正確的校驗和 - 對象可能被釋放後修改。 ***在malloc_error_break中設置一個斷點來調試。但是,當我遍歷代碼時,它工作正常。 – 2012-03-02 18:41:30

+0

如果在其中一個支持的平臺上使用Valgrind,它可能會更早得多。當然,好的舊GDB也是有效的。 – 0xC0000022L 2012-03-02 18:42:34

回答

5

問題是與這裏的代碼塊:

void _poly_lsr(polynom_t *p, int i) { 
    _poly_rsz(p, p->n + i); 
    memmove(p->factors + i, p->factors, sizeof(int)*(p->n)); // the problem is here! 
    memset(p->factors, 0, sizeof(int)*i); 
} 

當你調整你的多項式,可以重置它的數量,這意味着,當你加1,你滿溢的邊界1。您的多項式的陣列要解決,只需從memmove數減去i

memmove(p->factors + i, p->factors, sizeof(int)*(p->n - i)); 
+0

非常感謝。經過五個小時的休息時間與朋友們一起看電影,這似乎很明顯,我感到有點尷尬。 – Cybermage 2012-03-02 23:59:11