From: <all...@ma...> - 1997-12-31 05:44:56
|
Jay Johnson <jay...@ro...> writes: > /*allocate room for the points */ > obj->point_x = (float *)malloc(obj->npts * sizeof(float)); > obj->point_y = (float *)malloc(obj->npts * sizeof(float)); > obj->point_z = (float *)malloc(obj->npts * sizeof(float)); You can try to allocate memory for all coordinates at once: obj->point_x = (float*) malloc (3 * obj->npts * sizeof (float)); obj->point_y = obj->point_x + obj->npts; obj->point_z = obj->point_y + obj->npts; Or even (I have not tested it, but it should work after correcting typos): struct object* allocate_object (int npts, int npolys, int* nverts) { int i; int allverts = 0; struct object* obj; char* t; for (i = 0; i < npolys; i++) allverts += nverts[i]; obj = (struct object*) malloc (sizeof (struct object) + 3 * npts * sizeof (float) + npolys * sizeof (struct polygon) + allverts * sizeof (int) + 3 * allverts * sizeof (float)); if (obj == 0) { /* malloc failed (no free memory of this size). */ #if 1 /* * Temporary "solution". */ printf ("say something\n"); exit (1); #else /* * In this case you should test return value in caller and do something. * Stop parsing file, say message to user and draw what you have already. */ return 0; #endif } /* Set members of obj structure, like npts... (or do it in fill_object?). */ t = (char*) obj; t += sizeof (struct object); obj->point_x = (float*) t; t += npts * sizeof (float); obj->point_y = (float*) t; t += npts * sizeof (float); obj->point_y = (float*) t; t += npts * sizeof (float); obj->polys = (struct polygon*) t; t += npolys * sizeof (struct polygon); for (i = 0; i < npolys; i++) { obj->polys[i].verts = (int*) t; t += nverts[i] * sizeof (int); obj->polys[i].localpoint_x = (float*) t; t += nverts[i] * sizeof (float); obj->polys[i].localpoint_y = (float*) t; t += nverts[i] * sizeof (float); obj->polys[i].localpoint_z = (float*) t; t += nverts[i] * sizeof (float); } return obj; } But you should free only memory that you allocated with malloc (obj in this case). Allocating your objects in this way, probably you will not need to replace malloc. > How can I test the results of malloc when it crashes on me? malloc returns 0 in case of error (when there is not free memory of requested size or larger). Using function suggested above, it will be easier to test for malloc failure, because you will not have incomplete object which should be freed (to have no memory leaks in the program). |