Skip site navigation (1)Skip section navigation (2)
Date:      Mon, 13 May 2002 13:31:20 -0400
From:      mpd <mpd@rochester.rr.com>
To:        Paul Everlund <tdv94ped@cs.umu.se>
Cc:        freebsd-questions@FreeBSD.ORG
Subject:   OT: Re: C malloc question
Message-ID:  <20020513133120.A45757@rochester.rr.com>
In-Reply-To: <Pine.GSO.4.33.0205131845160.22929-100000@gren.cs.umu.se>; from tdv94ped@cs.umu.se on Mon, May 13, 2002 at 07:06:57PM %2B0200
References:  <Pine.GSO.4.33.0205131845160.22929-100000@gren.cs.umu.se>

next in thread | previous in thread | raw e-mail | index | archive | help
On Mon, May 13, 2002 at 07:06:57PM +0200, Paul Everlund wrote:
> Hi all!
> 
> I have a question regarding malloc and returning arrays in C.
> 
> The following C program is an example.
> 
> #include <stdlib.h>
> #include <string.h>
> 
> static char *init()
> {
>   char *str;
>   int i;
> 
>   str = (char *)malloc(sizeof(char), 128);
>   for(i = 0; i < 127; i++)
>     str[i] = "A";
>   str[i] = '\0';
>   return str;
> }
> 
> int main()
> {
>   int i;
> 
>   for(i = 0; i < 500000; i++)
>     init();
>   printf("%s\n", init());
>   return 0;
> }
> 
> This program takes up a lot of malloc'ed memory after a while,
> so how do one return arrays and free memory in the main function
> everytime the array have been used? I would like to not use fix-
> ed size arrays, as the real function should be general enough
> to handle all kind of array sizes.
> 
> As the size is known in the main function, I guess I could send
> in a buffer to get the data, as in init(char *buf), but I would
> like to avoid this.
> 
> What is the best solution for this problem?

Either what you said, or use a global variable.
Given the choice, I would pass the pointer to the function.

> 
> Thanks a lot in advance!
> 
> Best regards,
> Paul
> 

mike
-- 
___________________________________________________________
 
Pokey: "WE WERE LUCKY TO FIND THIS TIME CANOE!"
Little Girl: "YES!!!"
	- from "POKEY THE HIS FRIENDS"

To Unsubscribe: send mail to majordomo@FreeBSD.org
with "unsubscribe freebsd-questions" in the body of the message




Want to link to this message? Use this URL: <https://mail-archive.FreeBSD.org/cgi/mid.cgi?20020513133120.A45757>