2 Answers
2

You're allocting cn on the stack so when your cellGetNeighbors function is finished and returns, the value of cn (the cellGetNeighbors version of it) will no longer be valid and cn in cellMinNeighbor will be pointing at a chunk of the stack that is being used for something else.

You have two easy options:

Pass an array of eight struct cell into cellGetNeighbors so that the caller is responsible for allocating that memory.

Allocate cn on the heap (i.e. malloc) inside cellGetNeighbors and return it as you are now. The caller would, of course, have to free the cellGetNeighbors return value when it was finished with it (and this fact should be documented as part of the cellGetNeighbors interface).

I'd recommend the second option and I'd recommend building a separate cellFree function to properly free a single cell. The cellFree function is a good idea because your struct cell has a pointer in it and that pointer will need to be freed. This is, of course, complicated further if you ever need to use an array that doesn't have exactly eight elements; if that happens then you'll have to return the array size as well by adding an extra pointer argument to getCellNeighbors. If things get to that point then you'll want to add a separate struct:

I'm guessing that you have similar stack versus heap issues with cellCalculateKey as well.

And, you don't need to do this:

struct cell *cptr = &cn[0];
cellPrintData(&cn[2]);
return cptr;

The cn array will decay to a pointer without your intervention, just this is fine:

cellPrintData(&cn[2]);
return cn;

Furthermore, since I'm already writing a book here, you don't need to cast the return from malloc (or calloc or realloc or anything else that returns void *) in C and doing so can cover up problems. So, where you say this:

Looks like cellGetNeighbors is returning stack memory--it returns cptr, which points to &cn[0]. Once the method returns, anything you declared on the stack is no longer valid. You're duplicating the cells into that, so you probably just need to malloc-up the array. Note that you will need to eventually free that array too.