# Thread: Freeing dynamically allocated memory

1. ## Freeing dynamically allocated memory

I found this code on the internet. Its purpose is to allocate a contiguous memory block for a two-dimensional dynamic array.

Code:
```int** x;
int* temp;

x = (int**)malloc(dimension1_max * sizeof(int*));
temp = (int*)malloc(dimension1_max * dimension2_max * sizeof(int));
for (int i = 0; i < dimension1_max; i++) {
x[i] = temp + (i * dimension2_max);
}```
How should I free the memory allocated with such code?
I'd go for:

Code:
```free(x[0]);
free(x);```
Is my assumption correct? I also think I can "forget" the temp pointer because it points to the same memory block as x[0].

2. Yes.

3. Originally Posted by laserlight
Yes.
Thanks. Is the temp pointer actually needed at all? Can I replace it with x[0]?

4. You can replace temp with x[0] if you wish, as long as you only use x[0] after x has been given an initial value.

Incidentally, I suggest writing:
Code:
`x = malloc(dimension1_max * sizeof(x[0]));`
There is no need to cast the return value of malloc, and then you might as well make sizeof use x in some way so that if the type of x changes, the code would remain correct.

5. Yes, you can remove temp and work with x[0] directly:
Code:
```#include <stdio.h>
#include <stdlib.h>

#define TEST
#define N 10
#define M 5

int main()
{
int** p = (int**)malloc(N * sizeof(int*));
int k = 0;

if (p)
{
// Allocate one master block
p[0] = (int*)malloc((N * M) * sizeof(int));

// Split up the master block
for (int x = 1; x < N; ++x)
{
p[x] = p[0] + (x * M);
}

// Initialize the array
for (int x = 0; x < N; ++x)
{
for (int y = 0; y < M; ++y)
{
p[x][y] = k++;
}
}

#if defined(TEST)
// Print for testing
for (int x = 0; x < N; ++x)
{
for (int y = 0; y < M; ++y)
{
printf("%3d", p[x][y]);
}

putchar('\n');
}
#endif

// Clean up the mess
free(p[0]);
free(p);
}
}```

Popular pages Recent additions