开发者

segfault in fwrite on linux

开发者 https://www.devze.com 2023-04-05 12:21 出处:网络
I havea piece of C code where I try to write a buffer into an opened output file.I am getting a segmentation fault when I try to run the code.

I have a piece of C code where I try to write a buffer into an opened output file.I am getting a segmentation fault when I try to run the code.

if (fwrite(header, record_size, 1, uOutfile) != 1)
{
    return 0;
}

The header is a properly populated and I am able to print out the contents of the header.the size of the buffer header is definitely greater than the record_size.Is there anything else worth checking.?Any other reason where fwrite can cause a segfault.Gdbing the problem gave the following output

0x00007ffff6b7d66d in _IO_fwrite (buf=0x726d60, size=16, count=1, 开发者_开发知识库fp=0x738820) at iofwrite.c:43
43  iofwrite.c: No such file or directory.
    in iofwrite.c

it seems to suggest that the output file has not been created.how ever and ls -l on my directory shows the output file of size 0 bytes.

I would greatly appreciate if someone could throw some light on the problem.

EDIT: Code that opens the file:

outfd = open(out, O_RDWR|O_CREAT|O_TRUNC|O_LARGEFILE, 0664);
if (outfd == -1) {
    dagutil_panic("Could not open %s for writing.\n", out);
}
uOutfile = fdopen(outfd, "w");


I don't think there's enough here to know for sure what your problems are, but here are some thoughts:

  • Show us the code involving your FILE * (uOutFile) and your buffer (header) — we can then see if you're borking memory somewhere between.
  • Run your code through valgrind: You're getting a segfault, so it could probably catch what you're doing wrong.
  • In gdb, examine the contents of both header and uOutFile (not just the pointer, but the pointed-to-memory.) (You'll have to use some smarts to figure out if uOutFile looks right, but you should be able to up-or-down determine if header is correct.)

To add to this: my general debug strategy when I get segfaults is:

  1. gdb's backtrace. Tells me where the segfault happened. Usually, this is enough to uncover the dumb thing I did.
  2. Look at the pointers in the vincinity of the crash. Is the pointer correct, and is the pointed-to data correct? (esp. if you see something strange like 0xdeadbeef)
  3. Valgrind Valgrind Valgrind

(2 & 3 are in no particular order.)

0

精彩评论

暂无评论...
验证码 换一张
取 消