当我从终端使用gdb运行输出程序时,它总是以此功能的分段错误结束。 但是使用eclipse调试器运行它可以正常工作。
ssize_t
read_from_file(char *arg, unsigned char *buf, size_t max_buf_len) {
ssize_t result = 0;
FILE *f = fopen(arg, "r");
int c;
while (!feof(f)) {
size_t bytes_read;
bytes_read = fread(buf, 1, max_buf_len, f);
if (ferror(f)) {
result = -1;
break;
}
buf += bytes_read;
result += bytes_read;
max_buf_len -= bytes_read;
}
fclose(f);
return result;
}
来自gdb的错误消息
[Thread debugging using libthread_db enabled]
Using host libthread_db library "/lib/x86_64-linux-gnu/libthread_db.so.1".
Program received signal SIGSEGV, Segmentation fault.
_IO_feof (fp=0x0) at feof.c:35
35 feof.c: No such file or directory.
我尝试使用feof()
喜欢
while((c = fgetc(file)) != EOF)
但我得到的结果相同
[Thread debugging using libthread_db enabled]
Using host libthread_db library "/lib/x86_64-linux-gnu/libthread_db.so.1".
Program received signal SIGSEGV, Segmentation fault.
_IO_getc (fp=0x0) at getc.c:37
37 getc.c: No such file or directory.
有谁知道这个错误源自何处?
答案 0 :(得分:3)
请注意,condition()
始终是一个错误,因为在C中,文件结束条件仅在尝试阅读之后检测到,而之前 。
然后,你违反了ten commandments(2和6)中的两个,没有检查来自while (!feof(f))
的返回值,当你使用文件指针时,返回值可能为NULL并导致分段错误。
是的,无论你告诉我们关于你的IDE和调试的内容,你都会得到一个来自fopen
的NULL指针并将其传递给fopen()
,这实际上就是你得到的错误信息和问题标题:feof()
。
答案 1 :(得分:1)
您应该检查 @RequestMapping(value = EmpRestURIConstants.DUMMY_EMP, method = RequestMethod.GET)
public @ResponseBody Employee getDummyEmployee() {
logger.info("Start getDummyEmployee");
Employee emp = new Employee();
emp.setId(9999);
emp.setName("Dummy");
emp.setCreatedDate(new Date());
empData.put(9999, emp);
return emp;
}
返回值。