为何我的选择排序代码出现「stack smashing detected」错误?如何解决?
Let's break down why you're hitting that stack smashing error and how to fix it quickly.
The Root Cause: Array Out-of-Bounds Access
Look closely at the swap part in your in_sort function:
if (i != k) { int t = a[i]; a[i] = a[j]; a[j] = t; }
By the time you reach this code block, the inner for loop (for (j = i; j < l; j++)) has finished running. That means j is now equal to l (since the loop stops when j is no longer less than l).
But your array a only has valid indices from 0 to l-1—accessing a[l] (which is what a[j] points to here) is an out-of-bounds memory access. Since your array lives on the stack (allocated in main), writing to this invalid memory triggers the stack smashing protection built into most compilers, hence the error you're seeing.
You almost certainly meant to swap with the index of the minimum element you found, which is stored in k—not j.
The Fix
Replace j with k in the swap block. Here's the corrected in_sort function:
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[k]; // Use k instead of j a[k] = t; // Use k instead of j } } return a; }
Also, don't forget to include the required header for cout at the top of your code:
#include <iostream> using namespace std; // Or use std::cout directly if you avoid using namespace std
Quick Verification
After these changes, your code will run without the stack smashing error and correctly sort the array. The output will be:2 2 2 5 5 34 56 322 456 567
内容的提问来源于stack exchange,提问作者Ashik

