473,473 Members | 1,705 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

Malloc and recursion

(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
9 4432
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
> (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
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
> 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
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

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

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
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
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 thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
by: Peri | last post by:
I'm trying to create Python parser/interpreter using ANTLR. Reading grammar from language refference I found: or_expr::= xor_expr | or_expr "|" xor_expr For me it looks like infinite recursion....
12
by: da Vinci | last post by:
Greetings. I want to get everyone's opinion on the use of recursion. We covered it in class tonight and I want a good solid answer from people in the "know" on how well recursion is accepted...
43
by: Lorenzo Villari | last post by:
I've tried to transform this into a not recursive version but without luck... #include <stdio.h> void countdown(int p) { int x;
11
by: Aire | last post by:
On some small-memory systems, is it true that "malloc()" is not supported by the C library? Why is 'dynamic memory allocation' so avoided on such systems? What are major problems of using...
13
by: Thomas Barth | last post by:
Hi, I would like to create a file index like updatedb on Linux does as a part of my program, but I dont know how long the filenames could be. Therefore I want to use malloc to keep the size of the...
75
by: Sathyaish | last post by:
Can every problem that has an iterative solution also be expressed in terms of a recursive solution? I tried one example, and am in the process of trying out more examples, increasing their...
58
by: Jorge Peixoto de Morais Neto | last post by:
I was reading the code of FFmpeg and it seems that they use malloc just too much. The problems and dangers of malloc are widely known. Malloc also has some overhead (although I don't know what is...
20
by: athar.mirchi | last post by:
..plz define it.
35
by: Muzammil | last post by:
int harmonic(int n) { if (n=1) { return 1; } else { return harmonic(n-1)+1/n; } } can any help me ??
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
1
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
1
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...
1
muto222
php
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.