Mail Archives: djgpp/1998/05/21/05:00:47
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 <stdlib.h> 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 <stdio.h>
#include <stdlib.h> /* 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.
- Raw text -