[LCP] Question on setfub

Paul Gearon gearon at ieee.org
Fri Jul 20 04:29:26 UTC 2007


On Jul 19, 2007, at 9:36 PM, Ludwig Isaac Lim wrote:

> Hi:
> Hi:
>
>
>    Supposing I have the following functions:
>
> void  write_helper  (FILE  *fp)
> {
>     /* write stuff to fp */
>     fwrite(....,fp);
>
> }
>
>
> void  main_writer()
> {
>      FILE *fp;
>      char buff [MY_BUFF_SIZE];
>
>      fp = fopen("somefile","w");
>      setbuf(fp,  buff);     /* allocate buffer for fp */
>
>      fwrite(....,fp);   /* write to buffer */
>      fwrite(....,fp);
>      ...
>      write_helper(fp);
>
>      fclose(fp);
> }
>
>
>   Is the buffer declared in main_writer() visible in
> write_helper()? I mean, will the fwrite() in fp writes to
> same buffer in main_writer()?  Is the above code ok?

Yes, this is fine.

The buffer is allocated on the stack in the stack frame belonging to  
main_writer.  This frame is valid until the main_write function  
exits.  Since write_helper is called from within main_writer, the  
main_writer stack frame is still there, and the buffer is still valid.

To show a counter example, if the fp pointer were returned from  
main_writer and then passed on to write_helper, then the buffer would  
certainly be invalid.  An example of this code would be:

void more_writing(FILE  *fp)
{
     fwrite(....,fp);
}

FILE* start_writing()
{
      FILE *fp;
      char buff [MY_BUFF_SIZE];

      fp = fopen("somefile","w");
      setbuf(fp,  buff);     /* allocate buffer for fp */
      fwrite(....,fp);   /* write to buffer */
      fwrite(....,fp);
      return fp;  /* ERROR: contains reference to buff! */
}

void do_write(void)
{
      FILE* fp;
      fp = start_writing();
      more_writing(fp);
      fclose(fp);
}


Regards,
Paul



More information about the linuxCprogramming mailing list