[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

Re: programming



On Sun, 4 Nov 2001 16:56:58 +0100, martin f krafft <madduck@madduck.net> wrote:

> * Sebastiaan <S.Breedveld@ITS.TUDelft.NL> [2001.11.04 16:51:09+0100]:
> > while (fgets(buff, sizeof(buff)-1, filestream) != NULL)
> >         {
> > 	/* do something with the 'buff' variable */
> > 	}
> 
> char *buff = (char*)malloc(128);
> sizeof(buff) == 4   // on i32 machines
> 
> --> problem!

Depends on what "buff" is, its scope and how sizeof is used.

  #define BUFFSIZE 80
  size_t what_size (char a[BUFFSIZE])
  {
    /* looks like we know the size of "a", but functions receiving arrays
     * really only get a pointer to the first element of the array.
     */
    return (sizeof a / sizeof *a);
  }

  int main (void)
  { 
    char buff[BUFFSIZE];
    printf ("buff is %d or %d?\n", (long) sizeof(buff), (long) what_size(buff));
    return 0;
  }

  --> "buff is 80 or 4?"
  
But if you define your buffer globally:

  static buff[80] = "";

  size_t what_size (void)
  {
     return (sizeof buff / sizeof *buff);
  }

  int main (void)
  {
     printf ("buff[%d]\n", (long) what_size());
     return 0;
  }

  --> "buff[80]"

Just another reason why C is such a "dangerous" language. 

-- 
Eric G. Miller <egm2@jps.net>



Reply to: