Path: utzoo!mnetor!uunet!husc6!cmcl2!nrl-cmf!ames!umd5!mimsy!chris From: chris@mimsy.UUCP (Chris Torek) Newsgroups: comp.lang.c Subject: Re: CALLOC and MALLOC Message-ID: <10306@mimsy.UUCP> Date: 23 Jan 88 00:29:42 GMT References: <11415@brl-adm.ARPA> Organization: U of Maryland, Dept. of Computer Science, Coll. Pk., MD 20742 Lines: 40 In article <11415@brl-adm.ARPA> V4039%TEMPLEVM.BITNET@CUNYVM.CUNY.EDU (Stan Horwitz) writes: >Why do the basic memory allocation functions CALLOC and MALLOC clear >the newly allocated memory they yield? They do not. calloc sets the allocated memory either to all zero bytes or to integer zeroes (it is implemented as integers on Unix, but I do not know what the dpANS says). malloc sets nothing at all. >I ... am trying to build dynamic arrays ... yet each time I add a new >element of memory onto my array, all the previous elements are cleared. If you mean you are doing something like this: getthem() /* buggy */ { int nel, *el, v; nel = 0; el = NULL; while (scanf("%d", &v) == 1) { nel++; el = (int *)malloc(nel * sizeof(int)); if (el == NULL) panic("out of memory"); el[nel - 1] = v; } ... } then you are doing it wrong! To change the size of a previously allocated region, use `realloc', which copies as much data as you had before (if the region is growing) or as much as will fit (if it is shrinking). The example above continuously allocates more space, never releasing the previously-allocated space. -- In-Real-Life: Chris Torek, Univ of MD Comp Sci Dept (+1 301 454 7163) Domain: chris@mimsy.umd.edu Path: uunet!mimsy!chris