从文件读取到字符串数组时出现分段错误

时间:2015-10-04 15:39:00

标签: c++ string file-io segmentation-fault

我在字符串数组中赋值时遇到了奇怪的错误。它会间歇性地分配两到三个然后崩溃。

我正在尝试使用两个并行数组(一个字符串和一个整数)来实现一个简单的未排序字典,例如结构 这是我认为错误发生在代码中的位置。

std::ifstream infile1("out1.tmp");
std::string word;
while (getline(infile1,word)){
  std::istringstream iss(word);
  printf("stream created\n");
  if (!(iss >> bookone.keys[i]))
    break;
  i++;
}

bookone是一个包含公共字段的字典对象:keysindex。即使我将变量赋值移到类中,它也会以同样的方式出错。

让我最困惑的部分是它似乎在前几次迭代中起作用。

strace提供了这个:

open("out1.tmp", O_RDONLY)              = 5
read(5, "This\nEtext\nfile\nis\npresented\nby\n"..., 8191) = 8191
write(1, "stream created\n", 15stream created
)        = 15
write(1, "stream created\n", 15stream created
)        = 15
--- SIGSEGV {si_signo=SIGSEGV, si_code=SEGV_MAPERR, si_addr=0xd36ff8} ---
+++ killed by SIGSEGV +++
[1]    16430 segmentation fault  strace ./book macbeth.txt othello.txt

和valgrind给了我一堆这些:

==16499== Invalid read of size 8
==16499==    at 0x4EAB634: std::basic_istream<char, std::char_traits<char> >& std::operator>><char, std::char_traits<char>,  std::allocator<char> >(std::basic_istream<char, std::char_traits<char> >&, std::basic_string<char, std::char_traits<char>, std::allocator<char> >&) (in /usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.20)
==16499==    by 0x401673: main (in /home/luna/sauce/books/book)
==16499==  Address 0x5a00ca8 is 24 bytes before a block of size 568 alloc'd
==16499==    at 0x4C28C20: malloc (vg_replace_malloc.c:296)
==16499==    by 0x56C106C: __fopen_internal (iofopen.c:73)
==16499==    by 0x401555: main (in /home/luna/sauce/books/book)

0 个答案:

没有答案