
malloc/free question with Purify
Hi,
I'm still messing around with malloc/frees of structures,
esp. structures that point to other ones. (I'm trying to get
at the reason for a seg fault.) Purify dislikes this; it
says there is a Free Memory Read as well as a Freeing of
Unallocated Memory on the line marked with ***. I apologize
for the length; I tried to pare it down as much as possible.
Thanks in advance for any help you can give. This is very
similar to the problem I'm trying to solve; when I eliminate
the "free" in the change_values function, Purify is happier
but reports memory leaks (duh).
btw, Purify is a debugging tool on UNIX; it does an
evaluation of how memory is used in your programs.
-Jennie
---header file my_structs.h------
typedef struct{
char c;
int i;
float *values;
Quote:
} smallStruct;
typedef struct {
float f;
char *s;
smallStruct *ss;
Quote:
} myStruct;
===================================my_structs.c=======
#include <stdio.h>
#include <stdlib.h>
#include "my_structs.h"
#define ENOUGH 25
int change_values(myStruct *this, int num);
int main(void)
{
myStruct *arrayOstructs;
int i,k;
int returnVal;
int numStructs = 3;
arrayOstructs = malloc(sizeof(myStruct) * numStructs);
for (i = 0; i < numStructs; i++)
{
arrayOstructs[i].f = 1.0*i;
arrayOstructs[i].ss = (smallStruct *) malloc(sizeof(smallStruct));
arrayOstructs[i].ss->c = 'a';
arrayOstructs[i].ss->i = i;
arrayOstructs[i].ss->values = (float *) malloc(sizeof(float)*(i+1)*10);
for (k = 0; k < (i+1)*10; k++)
{
arrayOstructs[i].ss->values[k] = (i+1.0) * k;
}
}
change_values(arrayOstructs,numStructs);
for (i = 0; i < numStructs; i++)
{
free(arrayOstructs[i].ss);
free(arrayOstructs[i].ss->values); /* *** */
}
free(arrayOstructs);
return EXIT_SUCCESS;
Quote:
}
int change_values(myStruct this[], int num)
{
int j;
float *newarray;
newarray = (float *) malloc (sizeof(float) * 10);
for (j = 0; j < 10; j++)
{
newarray[j] = j;
}
for (j = 0; j < num; j++)
{
free(this[j].ss->values);
this[j].ss->values = newarray;
}
return 1;
Quote:
}
--
<>~<>~<>~<>~<>~<>~<>~<>~<>~<>~<>~<>~<>~<>~<>~<>~<>~<>~<>~<>~<>
Jennie Van Heuit, Alameda, CA http://www.*-*-*.com/
(remove the letter before the dot to respond via email)
"Wear sunscreen." -Mary Schmich (*not* Kurt Vonnegut)