|
-
March 23rd, 2002, 10:15 AM
#1
Problem with malloc(*void) and free(*void) in C / (better C) [urgent]
Hi, I'm a beginner to C/C++
I wrote a program for matrixoperations which should manage storage (memory) dynamicly.
The elements of a matrix should be float.
The problem is when allocating memory with malloc() I assign a float pointer to the return-value of malloc and when freeing the allocated memory I provide free with that pointer. I think that free() "thinks" that it just has to free a 4 byte memory block but indeed it is an array of floats to be freed.
What can I do ?
Here is a part of my sourcecode.
If you need more, please tell me:
//...
typedef struct
{
int nCol;
int nRow;
float* pContents;
} Matrix;
Matrix MatCreate(int m, int n)
{
Matrix z;
bool ok;
z.nCol = -1; z.nRow = -1; z.pContents = NULL;
if (m>-1 && n>-1)
{
z.pContents = (float*) malloc(z.nCol * z.nRow * sizeof(float));
ok = (z.pContents!=NULL);
if (ok)
{
z.nRow = m;
z.nCol = n;
}
}
return z;
}
//...
void MatDelete(Matrix z)
{
free(z.pContents);
}
//...
int main()
{
Matrix M1;
M1 = MatCreate(2,1);
//...
MatDelete(M1);
return 0;
}
Thanx 4 reading.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|