我正在编写一个必须遍历大量文本文件的程序,并且在非常大的文件上使用new []
和delete []
时遇到了问题。在第79,998次调用此函数时会发生此问题。
我已将问题缩小到此函数,该函数对前79997次调用执行完美,但在第79998次执行时出现seg错误。
通过gdb,我已将问题缩小到这一行。
*result = new char [end_index_exclusive - start_index_inclusive + 1]();
我只能怀疑delete []
实际上没有将内存释放回系统,因此在堆上分配了太多内存存在一些问题。
void getNewSubstring (char ** result, char * charArray, int start_index_inclusive, int end_index_exclusive){
if (*result != NULL)
delete[] *result;
*result = new char [end_index_exclusive - start_index_inclusive + 1](); //+ 1 for null terminating char
for (int x = start_index_inclusive; x < end_index_exclusive; x++)
(*result)[x - start_index_inclusive] = charArray[x];
(*result)[end_index_exclusive - start_index_inclusive] = '\0'; }
这是来自gdb的错误消息:
Program received signal SIGSEGV, Segmentation fault.
malloc()中的0x000000337007aaf9来自/lib64/libc.so.6in...--605-- VALGRIND
感谢