I want to malloc some memory, run some operations on that memory, and then have the result of those operations be persistent. An example might be if I have a 2-d persistent array that I want to do row-wise updates on.
void update(int **persistent, int row, int rowSize)
{
int *temp = (int*) malloc(sizeof(int) * rowSize);
//...do stuff with temp
persistent[row] = temp
}
What would be the safest way to do this in C without having to deep-copy the contents of temp to persistent[row]? If I do it the way I typed above without freeing temp, would that cause a memory leak even if I correctly free persistent later on?
EDIT: A related question I have is: if I try to free(temp) at the end of the function, I noticed that even though persistent[row] maintains a reference to the data at temp, the memory is released. Is this because of the way malloc/free are designed, so that whenever a free on a pointer is called, the memory is freed without checking for other live references to that memory?
That would only cause a memory leak if you don’t properly free the old pointer that was in
persistent[row], if it wasn’t NULL. As long as you free the old pointer before overwriting it withtempyou won’t have any problems as long as you correctly (row by row) freepersistent.