I could really use some help here. I can't figure out what's the problem is, so I've assumed it's all C's fault.
I have a function:
pf_plot32(Uint32 data[], Uint32 dl, pfplot pattern[], Uint8 pl, Uint32 pr, struct pf_path32 *path)
..Which takes a pointer to a structure:
struct pf_point32 {
Uint32 x;
Uint32 y;
};
struct pf_path32 {
Uint32 length;
struct pf_point32 *points[];
};
..And then plots points to it dynamically using this call/function:
...
path->points[length] = (struct pf_point32*)pf_allocate(sizeof(struct pf_point32));
path->points[length]->x = x;
path->points[length]->y = y;
length++;
...
void *pf_allocate (size_t size) {
void *p;
p = malloc(size);
if (p == NULL) {
sprintf(str, "Out of memory allocating size of %d\n", size);
pf_log(str);
}
return p;
}
Now the function worked perfectly making pretty little paths for me, until I tried to use it twice in a row. When I use it again, for no reason that I can even begin to comprehend, it changes the FIRST structure's length (not even the one that was passed to it!) to a crazy-num, something like "4153952" instead of the real length of something like "4".
How could this function be changing a structure that's not even given to it? I tracked down a possible location of the problem, but can't find the source. The evil backwards change seems to happen right after this line in the pf_plot32() function:
path->points[length] = (struct pf_point32*)pf_allocate(sizeof(struct pf_point32));
Why would allocating memory for one structure change an unrelated value (length) of an unrelated structure? Keep in mind, it's messing up the length of the PREVIOUS pf_path32 that was plotted, not the one that's currently being passed to it (which comes out fine).
Here is an example:
struct pf_path32 boundrypath;
pf_plot32(boundrydata, 2, boundrypattern, 11, 1, &boundrypath);
sprintf(str, "boundrypath.length = %d", boundrypath.length); pf_log(str);
struct pf_path32 blockpath;
pf_plot32(blockdata, 2, blockpattern, 11, 1, &blockpath);
sprintf(str, "boundrypath.length = %d", boundrypath.length); pf_log(str);
sprintf(str, "boundrypath.length is now = %d", boundrypath.length); pf_log(str);
..Outputs:
boundrypath.length = 4
blockpath.length = 4
boundrypath.length is now = 4153952
Thanks for reading my code. I hope someone can find a solution. Otherwise, I'm going to have to find a programming language that does what it's supposed to! :) Thanks again,
Steve