C에서 일부 다항식 연산을 구현하고 있습니다. 동적 인 구조체를 사용하여 정수 인수와 다항식 차수를 저장합니다. 다른 함수 외에도 p [X] * X 연산이 필요하므로 일종의 오른쪽 시프트를 구현하려고합니다.반복 호출 후 realloc()이 실패합니다.
그러나 약간의 교대 후 realloc()은 프로그램을 중단시킵니다. 이 예제에서는 세 번째 호출이지만 두 번째 및 네 번째 시프트를 시도하면 두 번째 이후에 충돌이 발생합니다. 당신이 당신의 다항식의 크기를 조정하면
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);
}
, 당신은 당신이 하나를 추가 할 때, 당신의 경계를 넘쳐, 그 의미 수,의 재설정 :
/* 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;
}
홀수를. 이 코드를 gcc로 실행하면이 오류가 발생합니다. '*** object for object 0x6868cf0 : 해제 된 객체에 대한 체크섬이 잘못되었습니다. - 객체가 해제 된 후 수정되었을 가능성이 있습니다. *** 디버깅을 위해 malloc_error_break에 중단 점을 설정하십시오. 그러나 코드를 단계별로 실행하면 정상적으로 작동합니다. –
지원되는 플랫폼 중 하나에서 Valgrind를 사용하면 훨씬 더 명확 해집니다. 물론 좋은 오래된 GDB만이 작동합니다. – 0xC0000022L