无法解决分段故障



你好,这里是新手我在运行程序时遇到分段错误,但找不到原因。我在谷歌上搜索过,知道它是由于内存冲突而发生的,但无法在我的代码中找到导致seg错误的原因。

下面的代码

#include <iostream>
#include<algorithm>
using namespace std;
int main()
{
int t, n, m;
int  arr[n];
cin >> t;
while (t--)
{
cin >> n >> m;
for (int i = 0; i < n; i++)
{
cin >> arr[i];
}
sort(arr, arr + n);
int distinct = 1;
for (int i = 1; i < n; i++)
{
if (arr[i] != arr[i - 1])
{
distinct++;
}
}
if (distinct < m)
{
cout << "YES" << endl;
}
else
{
cout << "NO" << endl;
}
}
return 0;
}

我使用lldb进行调试,结果如下:

divyangbhamat@Divyangs-MacBook-Air CodeChef % lldb ./a.out
(lldb) target create "./a.out"
Current executable set to '/Users/divyangbhamat/Documents/C++/CodeChef/a.out' (x86_64).
(lldb) run
Process 1316 launched: '/Users/divyangbhamat/Documents/C++/CodeChef/a.out' (x86_64)
1
5
6
1
2
1
5
3
Process 1316 stopped
* thread #1, queue = 'com.apple.main-thread', stop reason = EXC_BAD_ACCESS (code=1, address=0x7ffe00000007)
frame #0: 0x00007fff2029b328 libc++.1.dylib`unsigned int std::__1::__sort3<std::__1::__less<int, int>&, int*>(int*, int*, int*, std::__1::__less<int, int>&) + 4
libc++.1.dylib`std::__1::__sort3<std::__1::__less<int, int>&, int*>:
->  0x7fff2029b328 <+4>:  movl   (%rsi), %ecx
0x7fff2029b32a <+6>:  movl   (%rdi), %r8d
0x7fff2029b32d <+9>:  movl   (%rdx), %r9d
0x7fff2029b330 <+12>: cmpl   %r8d, %ecx
Target 0: (a.out) stopped.
(lldb) bt
* thread #1, queue = 'com.apple.main-thread', stop reason = EXC_BAD_ACCESS (code=1, address=0x7ffe00000007)
* frame #0: 0x00007fff2029b328 libc++.1.dylib`unsigned int std::__1::__sort3<std::__1::__less<int, int>&, int*>(int*, int*, int*, std::__1::__less<int, int>&) + 4
frame #1: 0x00007fff2029b3a2 libc++.1.dylib`unsigned int std::__1::__sort4<std::__1::__less<int, int>&, int*>(int*, int*, int*, int*, std::__1::__less<int, int>&) + 31
frame #2: 0x00007fff2029b40a libc++.1.dylib`unsigned int std::__1::__sort5<std::__1::__less<int, int>&, int*>(int*, int*, int*, int*, int*, std::__1::__less<int, int>&) + 37
frame #3: 0x0000000100003101 a.out`void std::__1::sort<int*, std::__1::__less<int, int> >(__first=0x00007ffe00000003, __last=0x00007ffe00000017, __comp=__less<int, int> @ 0x00007ffeefbff6f8) at algorithm:4125:5
frame #4: 0x0000000100002ffd a.out`void std::__1::sort<int*>(__first=0x00007ffe00000003, __last=0x00007ffe00000017) at algorithm:4133:5
frame #5: 0x0000000100002ef5 a.out`main at nobelPrize.cpp:16:9
frame #6: 0x00007fff20353621 libdyld.dylib`start + 1
frame #7: 0x00007fff20353621 libdyld.dylib`start + 1
(lldb)

#5在16.9行中表示问题,即排序函数,但无法在此处找到导致seg故障的原因

感谢您的帮助和时间

问题很可能是这两行:

int t, n, m;
int  arr[n];

首先定义变量n,该变量未初始化,并且具有不确定的值。

然后使用n的不确定值定义数组arr。在将n初始化为特定值之前,不能执行此操作。此处使用n会导致未定义的行为

第二行实际上还有另一个问题,因为它是一个可变长度的数组,而C++实际上并没有这些问题。请改用std::vector

为了解决这两个问题,你应该有这样的东西:

while (t--)
{
int n, m;
cin >> n >> m;
std::vector<int> arr(n);  // Create a vector of n elements
// ...
}

在更私人的注意事项上,该代码看起来像是为在线";竞争;或判断站点。此类网站不是教学或学习资源,您永远不应该将其用作学习编程语言或一般编程的方式。请拿一些好的C++书,参加一些课程来好好学习。

最新更新