Click to See Complete Forum and Search --> : Error In This Code ?????????


amit_iit
November 24th, 2004, 11:42 PM
Consider the following code

typedef union
{
struct /* Use this for the first array element*/
{
char title[20];
int count;
} header;
struct /* Use this for remaining array elements */
{
double x;
double y;
double z;
} data;
} Coord;

/* This function will allocate an array of n+1 elements. The first element will
/* the title and number of points (n) while the remaining n elements will be
/* individual coordinates.
*/
Coord *allocCoordArray(int n)
{
Coord *retval;
int i=0;
retval = malloc((n+1) * sizeof(Coord));
if (NULL = = retval)
return NULL;
strcpy (retval[i].header.title, “unknown” ) ;;
retval[0].header.count = n;
for (i = 1; i < n+1; i++)
{
retval[i].data.x = 0.0;
retval[i].data.y = 0.0;
retval[i].data.z = 0.0;
}
free(retval);
return retval;
}

Indicate with reasons any problems you see with the code.

amit_iit
November 24th, 2004, 11:46 PM
free(retval);
return retval;
}

Indicate with reasons any problems you see with the code.

i HAD EXPECTED THIS TO BE A PROBLEM BUT SUPRISINGLY WHEN I TRIED IT OUT IT WORKED ........THE FREE BEFORE RETURN DOES NOT AFFECT RETURN

Kheun
November 25th, 2004, 12:01 AM
Actually, there are 2 problems.

1. When you allocated n+1 Coord objects, you are using the extra 1 for the header. It is very difficult to understand your code and this should be separated into a different function to avoid the confusion.
2. Using memory after free(), is undefined behavior. In other words, it may work or crash anytime.

cilu
November 25th, 2004, 03:06 AM
First, I see no point in your union? What are you actually trying to do?

Second, I really don't see any reason in this?

free(retval);
return retval;

What good for to return an invalid pointer anyway?

Third, you should set the poitner to NULL after you release memory.

free(retval);
retval = NULL;
return retval; // still see no point in this statement

Ajay Vijay
November 25th, 2004, 03:28 AM
i HAD EXPECTED THIS TO BE A PROBLEM BUT SUPRISINGLY WHEN I TRIED IT OUT IT WORKED ........THE FREE BEFORE RETURN DOES NOT AFFECT RETURNIt may not! The reason why this "may" not cause runtime problem is simple: free has de-allocated memory from your program, it's still in "FREE" pool of its memory (or say, garbage collection). It (the same memory area) could be allocated to some other allocation request.

This is similar with the deletion of file (permanent deletion, not Recycle Bin issue) - OS removes the file entry from USED and moves it to FREE storage, so that it could be re-used further. This is the reason why some file-recovery programs work!