By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
434,720 Members | 2,244 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 434,720 IT Pros & Developers. It's quick & easy.

Malloc and recursion

P: n/a
(At least I think that this is recursion)
I've been getting stuck on this for far too long now.
I suspect that this can't be done how I want it to.
I'm thinking that I would need to store the mal in recurse() as an
array,
and then I would be able to free it.

Thanks for your help.
Matt
/* 11/04/06
Write a function containing malloc(), which calls itself five times
then returns. Write another function which frees all the memory. */

#include <stdio.h>
#include <stdlib.h>

void recurse(int *);

int main(void)
{
int a=0;
recurse(&a);
return 0;
}

void recurse(int *track)
{
int *mal = malloc(3*sizeof(int));
mal[0] = 0;
mal[1] = 1;
mal[2] = 2;
(*track)++;
if ((*track) < 5)
recurse(track);
}

Apr 11 '06 #1
Share this Question
Share on Google+
9 Replies


P: n/a
ballpointpenthief opined:
(At least I think that this is recursion)
I've been getting stuck on this for far too long now.
I suspect that this can't be done how I want it to.
I'm thinking that I would need to store the mal in recurse() as an
array,
and then I would be able to free it.

Thanks for your help.
Matt
/* 11/04/06
Write a function containing malloc(), which calls itself five times
then returns. Write another function which frees all the memory. */

#include <stdio.h>
#include <stdlib.h>

void recurse(int *);

int main(void)
{
int a=0;
recurse(&a);
return 0;
}

void recurse(int *track)
{
int *mal = malloc(3*sizeof(int));
mal[0] = 0;
mal[1] = 1;
mal[2] = 2;
(*track)++;
if ((*track) < 5)
recurse(track);
}


You were absolutely on the right track. I think what you wanted is:

/* 11/04/06
Write a function containing malloc(), which calls itself five
times
then returns. Write another function which frees all the
memory. */

#include <stdio.h>
#include <stdlib.h>

void recurse_malloc(int *);
void recurse_free(int *);

char *array[5];

int main(void)
{
int a=0;
recurse_malloc(&a);
recurse_free(&a);
return 0;
}

void recurse_malloc(int *track)
{
array[*track] = malloc(1);
*array[*track] = '0' + *track;

printf("alloc: %d '%c'\n",*track,*array[*track]);

(*track)++;
if ((*track) < 5)
recurse_malloc(track);
}

void recurse_free(int *track)
{
(*track)--;

printf("free: %d '%c'\n",*track,*array[*track]);

free(array[*track]);

if ((*track) != 0)
recurse_free(track);
}

--
"I once witnessed a long-winded, month-long flamewar over the use of
mice vs. trackballs...It was very silly."
(By Matt Welsh)

<http://clc-wiki.net/wiki/Introduction_to_comp.lang.c>

Apr 11 '06 #2

P: n/a
> (At least I think that this is recursion)
I've been getting stuck on this for far too long now.
I suspect that this can't be done how I want it to.
I'm thinking that I would need to store the mal in recurse() as an
array,
and then I would be able to free it.


Well of course you should save it to free it, but the question is
"Where".
One possible solution would be to save the pointer at the begining of
the
allocated array, and then pass that new allocated array to the next
function
call, which saves it in its own new array. Finally, the last array
address
could be returned and the free function would go in reverse direction
freeing the allocated arrays.
This can be thought of as a LIFO list...

--
Abdo Haji-Ali
Programmer
In|Framez

Apr 11 '06 #3

P: n/a
ed
On 11 Apr 2006 08:31:42 -0700
"ballpointpenthief" <Ma*************@gmail.com> wrote:
void recurse(int *track)
{
int *mal = malloc(3*sizeof(int));
mal[0] = 0;
mal[1] = 1;
mal[2] = 2;
(*track)++;
if ((*track) < 5)
recurse(track);
I don't see what the problem is calling free(mal) here, mal is a local
variable and should not be overwritten by subsequent calls to recurse.
}


I might be wrong of course. Let me know if I am.

--
Regards, Ed :: http://www.s5h.net
:%s/\t/ /g :: proud unix system person
:%s/Open Source/Free Software/g
Apr 11 '06 #4

P: n/a
> I don't see what the problem is calling free(mal) here, mal is a local
variable and should not be overwritten by subsequent calls to recurse.
}


I might be wrong of course. Let me know if I am.


You are absolutely right, however the required program should call
another "free" function to free the allocated arrays, instead of
freeing them in the same function

Abdo Haji-Ali
Programmer
In|Framez

Apr 11 '06 #5

P: n/a
ballpointpenthief wrote:
Write a function containing malloc(), which calls itself five times
then returns. Write another function which frees all the memory. */


<fx:innocentLook style="vlad"/>

#include <stdlib.h>

void example( int recurse )
{
if (sizeof( recurse ) == 0) malloc( 17 );
if (example) example(0), example(0), example(0), example(0), example(0);
}

void freeAllMemoryAllocatedByExample()
{} // alternative implementation: { exit( 0 ); }

int main(void)
{
example( 1 );
freeAllMemoryAllocatedByExample();
return 0;
}

--
Chris "not a Tuvela" Dollin
"To say that the human is thus and so is almost always to lie
automatically."
Apr 12 '06 #6

P: n/a

In article <e1**********@malatesta.hpl.hp.com>, Chris Dollin <ch**********@hp.com> writes:

void example( int recurse )
{
if (sizeof( recurse ) == 0) malloc( 17 );
if (example) example(0), example(0), example(0), example(0), example(0);


I fear example will all too often be true.

--
Michael Wojcik mi************@microfocus.com
Apr 12 '06 #7

P: n/a

I wrote:
..
I'm thinking that I would need to store the mal in recurse() as an
array,
and then I would be able to free it.


So then after reading the replies I tried this, and I think this must
be the simplest way of doing what I need to use this for.
Comments welcome.
===========
/* 11/04/06
Write a function containing malloc(), which calls itself five times
then returns. Write another function which frees all the memory. */

#include <stdio.h>
#include <stdlib.h>

void recurse(int *);
void recurse_free(int **, int *);

int **mal;

int main(void)
{
int a=0;
mal = NULL;
recurse(&a);
recurse_free(mal, &a);
return 0;
}

void recurse(int *track)
{

mal = realloc(mal, ((*track)+1)*sizeof(int *));
mal[*track] = malloc(3*sizeof(int));
mal[*track][0] = 0;
mal[*track][1] = 1;
mal[*track][2] = 2;
(*track)++;
if ((*track) < 5)
recurse(track);
}

void recurse_free(int **to_free, int *track)
{
while (*track)
{
free(to_free[*track]);
(*track--);
}
free(to_free);
}

Apr 12 '06 #8

P: n/a
ballpointpenthief wrote:

I wrote:
.
I'm thinking that I would need to store the mal in recurse() as
an array, and then I would be able to free it.


So then after reading the replies I tried this, and I think this
must be the simplest way of doing what I need to use this for.
Comments welcome.


Now that you've tried your hand at it, here's my solution:

#include <stdio.h>
#include <stdlib.h>

typedef struct data {
struct data *ptr;
} *dataptr;

/* --------------- */

dataptr recursemake(dataptr p, int depth)
{
dataptr newp;

printf("%d %p\n", depth, (void *)p);
if (0 == depth) return p;
else if (newp = malloc(sizeof *newp)) {
newp->ptr = p;
return recursemake(newp, depth - 1);
}
return newp;
} /* recursemake */

/* --------------- */

dataptr recursefree(dataptr p)
{
dataptr t;

if (p) {
printf("%p %p\n", (void*)p, (void*)p->ptr);
t = p;
p = recursefree(p->ptr);
free(t);
}
return p;
} /* recursefree */

/* --------------- */

int main(void)
{
dataptr p;

p = recursemake(NULL, 5);
p = recursefree(p);
return 0;
} /* main */
--
"If you want to post a followup via groups.google.com, don't use
the broken "Reply" link at the bottom of the article. Click on
"show options" at the top of the article, then click on the
"Reply" at the bottom of the article headers." - Keith Thompson
More details at: <http://cfaj.freeshell.org/google/>
Also see <http://www.safalra.com/special/googlegroupsreply/>
Apr 13 '06 #9

P: n/a
sgi wrote:
Hello Vladimir,
well i am new to C language and newsgroups
too. this c lang group is my first group and urs was the first post i
saw, but i was baffled by this new and strange syntax.
A few notes to begin with:

1) Don't top-post. Your reply belongs below, or interspersed with the
article you're replying to.

2) Do not snip attribution lines (the ones that say who said what, like
"sgi wrote:" above). They are important.

3) You seem to be using Google, and trying to do it properly. However,
do not click "Reply to author" as this send an e-mail, rather than
posting a reply to the newsgroup. There are two problems with this.
First, many people do not reveal their real e-mail addresses, so it's
likely they'll never see your reply. Second, unless there's a very
good reason for it, discussions should be in the open so all in the
newsgroup can see, learn, and correct.

I have corrected all three here:
Vladimir S. Oka opined:
array[*track] = malloc(1);
can u do things like this? wat is the index of the array? isn't the *
symbol used with pointers? how can a pointer be an index of an array?
or is it the value pointed to by the pointer that is the index of the
array? can u help me out in understanding this puzzle?


The construct *<pointer variable> is de-referencing the pointer, i.e.
it yields the value pointed to. Thus, in the line above, `*track`
reads the `int` value pointer `track` points to, an that value is then
used as index into the `array`.

I have used `malloc(1)` since I know `array` is an array of `char` and
size of `char` in C is always 1. It would have been much better had I
done something like:

array[*track] = malloc( sizeof array[*track] );

This guarantees that the above line will work regardless of how you
change the type of `array` elements.

As a side not: do not ever cast the value returned by `malloc()`. It is
not necessary, and it will only hide the problem if you forget to
#include <stdlib.h>.
that'll be a great help and encouragement to me. And also, i'd like
to know u better. I need some friend out here to help me out in this
confusing world of newsgroups etc. can u be my guide here?


For guidance on this particular group, it's sufficient to read the link
in my sig (and all links contained therein), and follow the
recommendations. There are also good sources on the Internet on the
general culture of Usenet (although groups differ). General advice is
to lurk (i.e. follow the traffic) of any group you'd like to
participate in for at least couple of months to get a feel of the
local customs. Google Groups can help here if you want to compress a
couple of months into couple of hours.

The above is almost certain to be enough guidance (provided you add a
good dose of common sense). Also, topicality and netiquette should be
on-topic in all groups (including this one).

--
But what can you do with it? -- ubiquitous cry from Linux-user
partner.
(Submitted by Andy Pearce, aj*@hpopd.pwd.hp.com)

<http://clc-wiki.net/wiki/Introduction_to_comp.lang.c>

Apr 14 '06 #10

This discussion thread is closed

Replies have been disabled for this discussion.