Date: Mon, 13 May 2002 19:06:57 +0200 (MEST) From: Paul Everlund <tdv94ped@cs.umu.se> To: <freebsd-questions@freebsd.org> Subject: C malloc question Message-ID: <Pine.GSO.4.33.0205131845160.22929-100000@gren.cs.umu.se>
next in thread | raw e-mail | index | archive | help
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? 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
Want to link to this message? Use this URL: <https://mail-archive.FreeBSD.org/cgi/mid.cgi?Pine.GSO.4.33.0205131845160.22929-100000>