free an array/pointer after returned

Hi,

I'm new in this forum and have same questions concerning pointers in C.

I have this two functions:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
int main (int argc, char **argv) {

	int i;
	double **ab = array();

	for (i=0; i<length; i++)
		printf("%f \t %e\n", ab[0][i], ab[1][i]);

	return 0;

}


double **array (void) {

	int ELEMENTS = 4;

	double
		*a = malloc(ELEMENTS * sizeof(double)),
		*b = malloc(ELEMENTS * sizeof(double)),
		**ab = malloc(2 * sizeof(double*));
	
	a[0] = 1; a[1] = 1; a[2] = 1; a[3] = 1;
	b[0] = 2; b[1] = 4; b[2] = 6; b[3] = 8;

	ab[0] = a;
	ab[1] = b;

	return ab;

}


My questions are:

1. How or where can I free the allocated memory in the main-program after returned it in array()?
2. How can I find out the dimensions of ab in the main-program?

Thank you and best regards,
grima
1. You call free() on every pointer you got from malloc() in reverse order.
2. You can't. You need to explicitly store the dimensions somewhere.
Hi Athar,

thank you for your quick reply.

Regarding your first answer:

Did you mean this order?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
double **array (void) {

	int ELEMENTS = 4;

	double
		*a = malloc(ELEMENTS * sizeof(double)),
		*b = malloc(ELEMENTS * sizeof(double)),
		**ab = malloc(2 * sizeof(double*));
	
	a[0] = 1; a[1] = 1; a[2] = 1; a[3] = 1;
	b[0] = 2; b[1] = 4; b[2] = 6; b[3] = 8;

	ab[0] = a;
	ab[1] = b;

        free(ab); free(b); free(a);

	return ab;

}


I think, this dosen't make sense, because, if I call the array()-function in the main-program, it would give a segmentation fault.

Regarding your second answer:
I found out a trick, with which I can get out the dimensions from the function itself.

Cheers,
grima


Well, obviously you can't use the array after you've freed it, so you have to free it in main() after you're done with it.
Actually, the order of free() calls is not important, other than the need to hold onto ab as long as you need its contents. It's invalid to refer to malloced memory after free() has been called on it.

Grima -- you say you "get out the dimensions from the function itself", but that needs explanation because you could be doing things that won't always work. I can't tell from what you said.
hi guys.....

To grim,u can use a delete[] function in the clib,to delete all the memory dat is unsed on the stack only since allocated memory in the heap
Topic archived. No new replies allowed.