[英]Why “*** stack smashing detected ***: <unknown> terminated Aborted (core dumped) ” error is showing in this code?
我正在以這種方式實現一個簡單的選擇排序代碼:
int* in_sort (int a[], int l)
{
int i, j, k, m;
for (i = 0; i < l - 1; i++) {
m = a[i];
k = i;
for (j = i; j < l; j++) {
if (a[j] < m) {
k = j;
m = a[j];
}
}
if (i != k) {
int t = a[i];
a[i] = a[j];
a[j] = t;
}
}
return a;
}
int main()
{
int a [] = {2, 5, 2, 56, 2, 567, 322, 456, 5, 34};
int *b = in_sort(a, 10);
for (int i = 0; i < 10; i++) cout << b[i] << ' ';
return 0;
}
但我收到了這個錯誤:
*檢測到堆棧粉碎* :終止中止(核心轉儲)
為什么會發生這種情況,我該如何解決? 我已經看過與此特定錯誤相關的其他答案,但無法理解我的情況出了什么問題。
我認為是這段代碼:
if (i != k) {
int t = a[i];
a[i] = a[j];
a[j] = t;
}
您可能指的是a[k]
,而不是a[j]
。 j
將等於l
,因此a[j]
剛好在數組的邊界之外。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.