I'm trying to allocate and free a pointer from a function, but for some reason when I'm running the code everything is working well, except when I'm doing a check with _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
I find memory leaks.
What can I do to fix this issue?
int mat_mul(float m1[ROWS][COLS], float m2[ROWS][COLS], float ***C)
{
int i, j, k;
float mul[ROWS][COLS];
int a = m1[2][1];
//Allocating memory for C.
if (a == 0) {
*C = (float **)malloc(sizeof(float*) * 10);
if (*C == NULL) return(-1);
for (i = 0; i < 10; i++) {
(*C)[i] = (float *)malloc(sizeof(float) * 10);
if ((*C)[i] == NULL) return(-1);
}
}
// Multiplication of the matrices m1,m2.
for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++) {
mul[i][j] = 0;
for (k = 0; k < 3; k++) {
mul[i][j] += m1[i][k] * m2[k][j];
}
}
}
for (i = 0; i < 2; i++) { (*C)[a][1] = mul[0][2]; (*C)[a][2] = mul[1][2]; } //Saving in C the variables needed.
if (a == 5) return (1); //Confirm that everything went as planned.
else return (-1);
}
{
int i, a;
float Angle1[6], Angle2[6];
float **Results;
printf_s("\n===========================\n\n");
printf_s("FORWARD KINEMATICS\n");
printf_s("---------------------------\n\n");
printf_s("Writing to file: data_q_to_xy_mat.csv from file: data_q.csv forward kinematic using matrix multiplication\n");
read_file("data_q.csv", &Angle1, &Angle2);
if (read_file("data_q.csv", &Angle1, &Angle2) != 0) {
printf_s("The file: data_q.csv was not opened\n");
printf_s("Failed to execute.\n\n");
}
else {
Angle_Converter(&Angle1, &Angle2);
for (i = 0; i < 6; i++) {
float Matrix1[ROWS][COLS] = { {cos(Angle1[i]),-sin(Angle1[i]),L1*cos(Angle1[i])},{sin(Angle1[i]),cos(Angle1[i]),L1*sin(Angle1[i])},{0,i,1} };
float Matrix2[ROWS][COLS] = { {cos(Angle2[i]),-sin(Angle2[i]),L2*cos(Angle2[i])},{sin(Angle2[i]),cos(Angle2[i]),L2*sin(Angle2[i])},{0,0,1} };
a = mat_mul(&Matrix1, &Matrix2, &Results);
}
if (a == -1) { printf_s("Failed to execute."); }
FILE* File;
fopen_s(&File, "data_q_to_xy_mat.csv", "w");
if (!File) return;
printf_s("The file: data_q.csv opened successfully\n");
printf_s("The file: data_q_to_xy_mat.csv opened successfully\n");
fprintf_s(File, "x,y\n");
for (i = 0; i < 6; i++) { fprintf_s(File, "%.1f,%.1f\n", Results[i][1], Results[i][2]); }
fclose(File);
printf_s("Done\n\n");
for (i = 0; i < 6; i++) { free(Results[i]); }//Freeing memory of "Results".
free(Results);
}