From owner-freebsd-questions Mon May 13 10: 7: 7 2002 Delivered-To: freebsd-questions@freebsd.org Received: from oxe.cs.umu.se (oxe.cs.umu.se [130.239.40.14]) by hub.freebsd.org (Postfix) with ESMTP id 4F83437B409 for ; Mon, 13 May 2002 10:07:00 -0700 (PDT) Received: from gren.cs.umu.se (rfc1413 says tdv94ped@gren.cs.umu.se [130.239.40.187]) by oxe.cs.umu.se (8.8.8/8.8.8) with ESMTP id TAA13537 for ; Mon, 13 May 2002 19:06:58 +0200 (MET DST) Date: Mon, 13 May 2002 19:06:57 +0200 (MEST) From: Paul Everlund To: Subject: C malloc question Message-ID: MIME-Version: 1.0 Content-Type: TEXT/PLAIN; charset=US-ASCII 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 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? Thanks a lot in advance! Best regards, Paul To Unsubscribe: send mail to majordomo@FreeBSD.org with "unsubscribe freebsd-questions" in the body of the message