I have a struct like this:
typedef struct tgPoligono { int numero_de_lados; CvPoint** cantos; float* lados; double* angulos; } *tgPoligono; In a function, I'm using it like this:
tgPoligono criar_tgPoligono(CvSeq* poligono){ int i; tgPoligono tg_poligono = (tgPoligono) malloc(sizeof(tgPoligono)); tg_poligono->numero_de_lados = poligono->total; tg_poligono->cantos = (CvPoint**) malloc(tg_poligono->numero_de_lados * sizeof(CvPoint*)); for(i= 0; i < tg_poligono->numero_de_lados; i++){ tg_poligono->cantos[i] = (CvPoint*)cvGetSeqElem(poligono, i); } tg_poligono->lados = (float*) malloc(tg_poligono->numero_de_lados * sizeof(float)); tg_poligono->angulos = (double*) malloc(tg_poligono->numero_de_lados * sizeof(double)); double* angulos = (double*) malloc(tg_poligono->numero_de_lados * sizeof(double)); for(i = 0; i < tg_poligono->numero_de_lados; i++){ CvPoint* pt_0 = tg_poligono->cantos[((i == 0)?(tg_poligono->numero_de_lados - 1):(i - 1))]; //Canto anterior CvPoint* pt_1 = tg_poligono->cantos[i]; //Canto atual CvPoint* pt_2 = tg_poligono->cantos[(i + 1) % tg_poligono->numero_de_lados]; //Canto seguinte //Calculo a distancia entre dois cantos, o que retorna o comprimento do lado do poligono tg_poligono->lados[i] = sqrt(((pt_1->x - pt_2->x)*(pt_1->x - pt_2->x)) + ((pt_1->y - pt_2->y)*(pt_1->y - pt_2->y))); //Calculo o cosseno do angulo correspondente ao ponto atualmente avaliado tg_poligono->angulos[i] = cosseno(pt_0, pt_2, pt_1); angulos[i] = cosseno(pt_0, pt_2, pt_1); } return tg_poligono; } Ok, my problem is with the tg_poligono->angulos tg_poligono->lados works fine but tg_poligono->angulos fails with apparently no reason!
when I use de function in my program (inside a for statment), the code above works for a while and then fails with no message.
If I comment the following lines, the program work fine, with no errors:
tg_poligono->angulos = (double*) malloc(tg_poligono->numero_de_lados * sizeof(double)); ... tg_poligono->angulos[i] = cosseno(pt_0, pt_2, pt_1); If you look at my code, you'll see a test that i do:
double* angulos = (double*) malloc(tg_poligono->numero_de_lados * sizeof(double)); ... angulos[i] = cosseno(pt_0, pt_2, pt_1); Its the same thing but not using the struct and it works fine.
ps.: I'm using opencv functions on this code, but it's unrelated with the problem. the function cosseno(pt_0, pt_2, pt_1) works fine, I sure of that. It's a C code, I can't use C++.
mallocis not needed and may hide an error. I suggest you remove the casts and let the compiler tell you about the possibly relevant error.