尝试在C ++程序上调试EXEC_BAD_ACCESS错误。程序将作为输入数字转换为字符串。然后我想返回生成最大可能数的整数的排序。
主要是
int main() {
// Number of ints to input
int n;
std::cin >> n;
vector<string> a(n);
// Input numbers as strings
for (size_t i = 0; i < a.size(); i++) {
std::cin >> a[i];
}
std::sort(a.begin(), a.end(), is_greater_than_or_equal);
std::cout << largest_number(a);
std::cout << std::endl;
return 0;
}
使用lldb,看起来错误来自sort / is_greater_than_or_equal函数。
is_greater_than_or_equal是
bool is_greater_than_or_equal(string n1, string n2) {
int l1 = n1.length();
int l2 = n2.length();
int min = (l1 < l2) ? l1 : l2;
for (int i = 0; i < min; i++) {
// First digit is strictly larger
if (n1[i] > n2[i]) {
return true;
// First digit is strictly lower
} else if (n1[i] < n2[i]) {
return false;
// First digits are the same
} else {
// If first is single digit
if (l1 == 1) {
return true;
// If the second is single digit
} else if (l2 == 1) {
return false;
// If they're both multiple digits
} else {
int j = i + 1;
// Keep checking until hitting min
while (j < min) {
if (n1[j] > n2[j]) {
return true;
} else if (n1[j] < n2[j]) {
return false;
} else {
j++;
}
}
// If min was hit and nothing was returned
// choose integer with lowest length
if (l1 > l2) {
return false;
}
return true;
}
}
}
return false;
}
使用lldb检查后,似乎sort函数继续经过a.end()
- 我相信这是导致错误的原因,但我不确定为什么会发生这种情况。原因是检查对is_greater_than_or_equal的调用会显示类似
(lldb) fr v
(std::__1::string) n1 = "9"
(std::__1::string) n2 = "2"
(int) l1 = 0
(int) l2 = 0
(int) min = 0
起初然后,过了一会儿,他们就变成了
(lldb) fr v
(std::__1::string) n1 = ""
(std::__1::string) n2 = ""
(int) l1 = 0
(int) l2 = 0
(int) min = 0
显然不应该发生(顺便说一句,我在分配l1和l2之前设置了断点,这就是长度不匹配的原因 - 这个点实际上只是看n1和n2)。
lldb的输出是
(lldb) r
Process 7405 launched: '/Users/etc' (x86_64)
100
2 8 2 3 6 4 1 1 10 6 3 3 6 1 3 8 4 6 1 10 8 4 10 4 1 3 2 3 2 6 1 5 2 9 8 5 10 8 7 9 6 4 2 6 3 8 8 9 8 2 9 10 3 10 7 5 7 1 7 5 1 4 7 6 1 10 5 4 8 4 2 7 8 1 1 7 4 1 1 9 8 6 5 9 9 3 7 6 3 10 8 10 7 2 5 1 1 9 9 5
Process 7405 stopped
* thread #1: tid = 0x2f2a6, 0x00007fff97c82051 libsystem_platform.dylib`_platform_memmove$VARIANT$Ivybridge + 49, queue = 'com.apple.main-thread', stop reason = EXC_BAD_ACCESS (code=1, address=0x0)
frame #0: 0x00007fff97c82051 libsystem_platform.dylib`_platform_memmove$VARIANT$Ivybridge + 49
libsystem_platform.dylib`_platform_memmove$VARIANT$Ivybridge:
-> 0x7fff97c82051 <+49>: rep
0x7fff97c82052 <+50>: movsb (%rsi), %es:(%rdi)
0x7fff97c82053 <+51>: popq %rbp
0x7fff97c82054 <+52>: retq
我不确定如何解释这个输出,也不完全清楚这种内部运作方式。