www.delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/1997/01/03/17:16:51

Message-ID: <32CD81C6.15E9@pobox.oleane.com>
Date: Fri, 03 Jan 1997 23:01:42 +0100
From: Francois Charton <deef AT pobox DOT oleane DOT com>
Organization: CCMSA
MIME-Version: 1.0
To: Andreas Vernersson <hubb AT freenet DOT hut DOT fi>
CC: djgpp AT delorie DOT com
Subject: Re: Calloc & Malloc
References: <1 DOT 5 DOT 4 DOT 16 DOT 19970103144936 DOT 0e97301e AT freenet DOT hut DOT fi>

Andreas Vernersson wrote:
> 
> I was programming on a "big" project now, when i sometimes began getting
> Floating point exeptions at random positions in the code. (Reported
> by symify). I double and tripplechecked the code but i couldn't find
> anything strange. I was using malloc to allocate mem then, but i got
> suspicius and changed all malloc's to calloc's and everything worked
> exactly as i wanted. So.. whats the difference between malloc
> and calloc, or is it some known "feature" of malloc?
> 

When you call malloc(), you just reserve a block of memory for future 
use. While calloc() also sets all of it to zero. If your program behaves 
this way, it means that you are using some variable (allocate through 
malloc()) without initialising it, like in

float *a;
a=(float *)malloc(n*sizeof(float));
b=cos(a[2]+3.0);

as you haven't put any value into a[2] before using it, it contains 
garbage, which sometime work, and sometime cause your errors (hence the 
randomness you noticed). 

With calloc() this won't happen : a[2] will be set to zero... but the is 
pushing the dust under the carpet : the bug in your program is still 
there... 

Francois

- Raw text -


  webmaster     delorie software   privacy  
  Copyright © 2019   by DJ Delorie     Updated Jul 2019