Question

I am trying to test fwrite. I am trying to write a usecase in which fwrite fails. Here is waht i tried.

#include <stdio.h>
#include <errno.h>
int main()
{
        char arr[6] = "manty";
        int ret;
        FILE *fp;
        printf("Before fwrite - errno - %d\n", errno);
        // fp = fopen("fwrite_test.txt", "w+");
        ret = fwrite(arr, sizeof(arr) + 2, 1, fp);
        printf ("ret - %d errno - %d ferror - %d\n", ret, errno, ferror(fp));
        return 0;
}

By wantedly commenting fopen() I thought fwrite will return an error. But it gives a segmentation fault.

How cani test fwrite()?

Was it helpful?

Solution 2

fwrite(3) may sometimes call the write(2) syscall, but not always, since stdio(3) is buffered (see setvbuf(3) for more). And fwrite will fail if write is failing.

You could limit the file size setrlimit(2) with RLIMIT_FSIZE (and install or ignore a SIGXFSZ signal(7) handler). In particular by using the ulimit builtin of bash shell. Then you could fwrite a big enough data buffer (larger than the limit). You could also set quotas on a file system (see quotactl(2), quotaon(8) etc...) then write over quota limits. At last, you could write in a small filesystem above its capacities (see Example section of losetup(8) to make a tiny filesystem...). In all these cases write will fail (so fwrite too).

OTHER TIPS

Your uninitialized variable fp here results in undefined behavior, which in your case is leading to a crash since your are trying to write on memory that is outside your process scope.

In order to write test cases for fwrite you will need to avoid situations that can cause undefined behavior, such as this one and some listed by leeduhem , and then pass your parameters as you wish to test them.

I believe it is much easy to write testcases for the rightnecss of fwrite() instead of for the falures of it, because many conditions that may cause fwrite() to fail, such as uninitialized input buffer, write more data than the input buffer actually has, uninitialized file stream, will lead to undefined behaviors according to C standard.

So under these conditions, it is hard to say whether you are testing fwrite() or are exploring the actual behaviors of these undefined behaviors in your specific testing circumstance.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top