From owner-freebsd-questions Mon May 13 10:32:25 2002 Delivered-To: freebsd-questions@freebsd.org Received: from roc-66-66-120-36.rochester.rr.com (roc-66-66-120-36.rochester.rr.com [66.66.120.36]) by hub.freebsd.org (Postfix) with ESMTP id 5DF2C37B401 for ; Mon, 13 May 2002 10:32:12 -0700 (PDT) Received: by roc-66-66-120-36.rochester.rr.com (Postfix, from userid 1000) id 7C6CE901A00; Mon, 13 May 2002 13:31:20 -0400 (EDT) Date: Mon, 13 May 2002 13:31:20 -0400 From: mpd To: Paul Everlund Cc: freebsd-questions@FreeBSD.ORG Subject: OT: Re: C malloc question Message-ID: <20020513133120.A45757@rochester.rr.com> References: Mime-Version: 1.0 Content-Type: text/plain; charset=us-ascii Content-Disposition: inline User-Agent: Mutt/1.2.5.1i In-Reply-To: ; from tdv94ped@cs.umu.se on Mon, May 13, 2002 at 07:06:57PM +0200 Sender: owner-freebsd-questions@FreeBSD.ORG Precedence: bulk List-ID: List-Archive: (Web Archive) List-Help: (List Instructions) List-Subscribe: List-Unsubscribe: X-Loop: FreeBSD.ORG 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 > #include > > 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