fclose() causing segmentation fault

与世无争的帅哥 提交于 2019-11-27 15:49:43
Jonathan Graehl
valgrind --db-attach=yes --leak-check=yes --tool=memcheck --num-callers=16 --leak-resolution=high ./yourprogram args

It's very likely the segfault is caused by memory corruption on the heap, not anything that's affecting locals. Valgrind will immediately show you the first wrong access you make.

Edit: The --db-attach option to valgrind has been deprecated since release 3.10.0 in 2014. The release notes state:

The built-in GDB server capabilities are superior and should be used
instead. Learn more here:

http://valgrind.org/docs/manual/manual-core-adv.html#manual-core-adv.gdbserver

one error i notice is this line:

 *chrome = (char *) malloc ((size_t) strlen(field));

which should be:

 *chrome = (char *) malloc ((size_t) strlen(field)+1);

This is because a string has a closing 0 at the end which you also have to make room for

Best guess is that some other part of your code is corrupting memory through a buffer overrun or similar bug.

Although unlikely to be the cause, you have a potential overrun condition in your filename array when the full filename exceeds 100 chars.

I would suggest using a debugger to watch for changes in the memory location used by the merbaseIn variable.

Generic Pointer Problem

C is a great language but it does require that you not clobber your own memory. Besides the problem previously noted where the malloc is 1 byte short, you may have other pointer problems.

I would suggest using a memory debugger. In the past, Electric Fence was rather popular but these days I hear more about valgrind. There are lots of other choices.

mouviciel

In addition to error found by reinier, I suspect that:

free(chromosome);

should be followed by:

chromosome = NULL;

in order to prevent potential usage of a no longer valid value.

why this FILE** filePtr if only this FILE* filePtr would be enough ? just a thought...

valgrind with memcheck is definitely the right tool to discover the cause of the segmentation fault. To use a debugger with valgrind, note that the --db-attach option to valgrind has been deprecated since Valgrind 3.10.0 was released in 2014. The release notes state:

The built-in GDB server capabilities are superior and should be used
instead. Learn more here:

http://valgrind.org/docs/manual/manual-core-adv.html#manual-core-adv.gdbserver

Review every place you used "malloc" and see if you made a mistake.

For example, I was putting lines read from a file into a char**, but I incorrectly malloced it as:

my_list = malloc(sizeof(char) * num_lines_found_in_file);

When it should have been:

my_list = malloc(sizeof(char*)* num_lines_found_in_file);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!