Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
483 views
in Technique[技术] by (71.8m points)

c - Unsuccessful fread() of int stored in binary file, segmentation fault


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You may have undefined behavior, with the following scenario:

  • int nbins; does not initialize nbins, so it contains junk data, potentially a very large number.

  • fread(&nbins, sizeof(int), 1, fd); is not tested so could fail and keep nbins uninitialized. Read about fread.

  • printf("nbins = %d", nbins); has no and is not followed by an explicit fflush so don't show anything (since stdout is usually line-buffered).

  • coords = malloc(nbins * sizeof(float)); would request a huge amount of memory, so would fail and get NULL in coords

  • fread(coords, sizeof(float), nbins, fd); writes to the NULL pointer, giving a segmentation violation, since UB

You are very lucky. Things could be worse (we all could be annihilated by a black hole). You could also experiment some nasal demons, or even worse, have some execution which seems to apparently work.

Next time, please avoid UB. I don't want to disappear in a black hole, so bear with us.

BTW, if you use GCC, compile with all warnings and debug info : gcc -Wall -Wextra -g. It would have warned you. And if it did not, you'll get the SEGV under the gdb debugger. On Linux both valgrind and strace could have helped too.

Notice that useless initialization (e.g. an explicit int nbins = 0; in your case) don't harm in practice. The optimizing compiler is likely to remove them if they are useless (and when they are not useless, as in your case, they are very fast).

Mandatory read

Lattner's blog: What Every C Programmer should know about UB. Related notion: the As-if rule.

Read also the documentation of every function you are using (even as common as printf).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...