【发布时间】:2018-03-07 03:59:03
【问题描述】:
我知道 Seg 错误通常是由无效的内存访问引起的,所以我认为问题可能在于我如何初始化传递给 split 函数的二维动态数组。但是,我花了几个小时查看它,似乎找不到问题。
使用 valgrind 我得到以下信息:
==31912== Command: ./Project1 Data.txt
==31912==
==31912== Use of uninitialised value of size 8
==31912== at 0x4016C6: split(long**, long**, long**, long, long) (in /home/tony/Project1)
==31912== by 0x400E5F: main (in /home/tony/Project1)
==31912==
==31912== Invalid read of size 8
==31912== at 0x4016C9: split(long**, long**, long**, long, long) (in /home/tony/Project1)
==31912== by 0x400E5F: main (in /home/tony/Project1)
==31912== Address 0x41d7894956415741 is not stack'd, malloc'd or (recently) free'd
==31912==
==31912==
==31912== Process terminating with default action of signal 11 (SIGSEGV)
==31912== General Protection Fault
==31912== at 0x4016C9: split(long**, long**, long**, long, long) (in /home/tony/Project1)
==31912== by 0x400E5F: main (in /home/tony/Project1)
==31912==
==31912== HEAP SUMMARY:
==31912== in use at exit: 1,248 bytes in 81 blocks
==31912== total heap usage: 89 allocs, 8 frees, 97,119 bytes allocated
==31912==
==31912== LEAK SUMMARY:
==31912== definitely lost: 304 bytes in 1 blocks
==31912== indirectly lost: 304 bytes in 38 blocks
==31912== possibly lost: 0 bytes in 0 blocks
==31912== still reachable: 640 bytes in 42 blocks
==31912== suppressed: 0 bytes in 0 blocks
==31912== Rerun with --leak-check=full to see details of leaked memory
==31912==
==31912== For counts of detected and suppressed errors, rerun with: -v
==31912== Use --track-origins=yes to see where uninitialised values come from
==31912== ERROR SUMMARY: 2 errors from 2 contexts (suppressed: 0 from 0)
Segmentation fault (core dumped)
valgrind 似乎认为是罪魁祸首的 split 函数是:
void split(long** arr, long** arrL, long** arrR, long median, long size){
//split data in half by x value -- takes in array sorted by x
for (long i = 0; i < size -1; i++){
if (i <= median){ //split data in half by x coord
arrL[i][0] = arr[i][0]; //x
arrL[i][1] = arr[i][1]; //y
}else{
arrR[i][0] = arr[i][0];
arrR[i][1] = arr[i][1];
}
}
}
在我的主函数中,我初始化数组,然后像这样调用 split():
arrL = new long*[median + 1];//add one to make sure there is enough room
arrR = new long*[median + 1];
for(long i = 0; i < median + 1; i++){
arrL[i] = new long[1];
arrR[i] = new long[1];
}
split(arr, arrL, arrR, median, size); //splits data
任何帮助将不胜感激!
【问题讨论】:
-
如果您使用
std::vector<std::vector<long>>,使用vector::at()将或应该通过std::out_of_range抛出异常向您显示错误。 -
如果您在启用调试信息的情况下进行编译 (
gcc -g),valgrind 通常会在报告问题时指向您的例程中的行号。你试过吗? -
See this example。使用
vector然后at()调用揭示了我的回答指出的错误。如果您仍然遇到问题,那么您很可能正在创建其他越界访问,可以使用该链接中的技术轻松诊断。
标签: c++ segmentation-fault valgrind dynamic-arrays