From: flux AT stack DOT nl (Mark van der Aalst) Newsgroups: comp.os.msdos.djgpp Subject: Re: Re-Mallocing an array... Date: 21 May 1998 09:15:05 +0200 Organization: MCGV Stack, Eindhoven University of Technology, the Netherlands. Lines: 54 Message-ID: <6k0k9p$aof@toad.stack.nl> References: <6jv6s8$kn1 AT nnrp4 DOT farm DOT idt DOT net> <35635D05 DOT 69D AT cs DOT com> NNTP-Posting-Host: toad.stack.nl To: djgpp AT delorie DOT com DJ-Gateway: from newsgroup comp.os.msdos.djgpp Precedence: bulk John M. Aldrich (fighteer AT cs DOT com) wrote: > Chia wrote: > > > > foo = (int *)malloc( sizeof(int) * 10); > > > > And then I want to change it to hold 20 ints. So, I figured I'd free it and > > then remalloc it. > > > > free(foo); > > foo = (int *)malloc( sizeof(int) * 20); > > > > but this crashes. How do I do this, then? This can't crash (assuming your machine has at least 80 bytes of memory :) *if* you included as a header file. If you didn't the program results in undefined behaviour and might indeed, among other things, crash. Another hint ; lose the int * casts, they don't buy you anything, worse they hide possible proto type mismatches. E.g. if you don't have stdlib.h and use a cast malloc() will return an int wich will be cast to a pointer ... nasty stuff, anyway this should do it ; #include #include /* aha ! */ int main(void) { int *foo = malloc(sizeof *foo * 10); if(foo) /* we malloced okay */ { free(foo); foo = malloc(sizeof *foo * 20); /* or just (even if foo == NULL) foo = realloc(foo, sizeof *foo * 20); */ if(!foo) puts("damn"); else free(foo); } else puts("darn"); return 0; } If you manage to crash this program I'll eat my hat. Cheers, flux.