what's wrong with the file pointer?

Started by kapokia, January 22, 2013, 06:33:36 AM

Previous topic - Next topic

kapokia

The two pieces of codes seemed as the same, but the output results are different.

This one goes correctly:
#include <stdio.h>

main()
{
FILE *fp = fopen("test.txt", "rb");
unsigned char buf[4];
while (fread(buf, 1, 1, fp))
{
printf("%s", buf);
memset(buf, 0, 1);
}
}


This one is incorrect:
#include <stdio.h>

void read(FILE *fp)
{
unsigned char buf[4];
while (fread(buf, 1, 1, fp))
{
printf("%s", buf);
memset(buf, 0, 1);
}
}

main()
{
FILE *fp = fopen("test.txt", "rb");
read(fp);
}


What's wrong with the second one?


kapokia

Quote from: CLR on January 22, 2013, 06:59:29 AM
Uninitialized buffer?
Neither the first one nor the second one initialized.
Both compiled and runnable, but the output result of the second one is wrong.

woody

#3
You should always memset a local buffer before any operation and you should do it complete. Not just the first element.
And it is good practice to prototype your read(). There are more functions with that name but but different arguments.
So the reason is a garbage on the stack that must be cleared.
This should work:

#include <stdio.h>

void read(FILE *fp);

void read(FILE *fp)
{
    unsigned char buf[4];
    memset(buf, 0, sizeof buf);
    while (fread(buf, 1, 1, fp))
    {
        printf("%s", buf);
    }
}

main()
{
    FILE *fp = fopen("test.txt", "rb");
    read(fp);
}


Woody

kapokia

Quote from: woody on January 22, 2013, 11:40:18 AM
You should always memset a local buffer before any operation and you should do it complete. Not just the first element.
And it is good practice to prototype your read(). There are more functions with that name but but different arguments.
So the reason is a garbage on the stack that must be cleared.
This should work:

#include <stdio.h>

void read(FILE *fp);

void read(FILE *fp)
{
    unsigned char buf[4];
    memset(buf, 0, sizeof buf);
    while (fread(buf, 1, 1, fp))
    {
        printf("%s", buf);
    }
}

main()
{
    FILE *fp = fopen("test.txt", "rb");
    read(fp);
}

Woody
Thanks a lot. It works correctly.