When I compile this code on gcc using linux ubuntu 11.04
Code:
#include <stdio.h>
#include <stdlib.h>
float *mult_matrix(int n, float *p, float *q);
float *get_matrix(int m, int n);
void show_matrix(int m, int n, float *p);
int main(void)
{
int n;
float *a, *b, *x;
printf("\nEnter the size of the linear system: \n");
scanf("%d", &n);
a=get_matrix(n, n);
show_matrix(n, n, a);
b=get_matrix(n, 1);
show_matrix(n, 1, b);
x=mult_matrix(n, a, b);
show_matrix(n, 1, x);
free(a);
free(b);
free(x);
return 0;
}
float *mult_matrix(int n, float *p, float *q)
{
int i, j;
float *x;
x=(float *)malloc((n)*sizeof(float));
if (!x) {
printf("NULL pointer detected. Exiting ...");
exit(1);
}
for(i=0; i<n; i++) {
*x=0;
x++;
}
x=x-n;
for (i=0; i<n; i++) {
for(j=0; j<n; j++) {
*x=*x+(*p)*(*q);
p++;
q++;
x++;
}
q=q-n;
}
x=x-n;
return x;
}
float *get_matrix(int m, int n)
{
int i, j;
float *a;
a=(float *)malloc((m*n)*sizeof(float));
if (!a) {
printf("NULL pointer detected. Exiting ...");
exit(1);
}
for (i=0; i<m; i++) {
for (j=0; j<n; j++) {
printf("\nEnter with the element a%d%d of the matrix:", i+1, j+1);
scanf("%f", a);
a++;
}
}
a=a-m*n;
return a;
}
void show_matrix(int m, int n, float *p)
{
int i, j;
printf("\n");
for (i=0; i<m; i++) {
printf("\n");
for (j=0; j<n; j++) {
printf(" %f ", *p);
p++;
}
}
printf("\n");
p=p-m*n;
}
I got this message on the end of the program after running it normally on the terminal:
Code:
*** glibc detected *** ./a.out: double free or corruption (out): 0x097d5058 ***
It means that the program or the compiler frees the pointers automatically so I dont have to use free()? Or this dont make any sense at all? Please, I need some help. Cheers.