arrays - "*** stack smashing detected ***: ./a.out terminated Aborted (core dumped)"- 数组插入

标签 arrays insertion

我从 Internet 上获得了以下代码,用于在数组中插入一个元素。我的问题是“如何增加数组的大小,尤其是在第一次插入时,每次执行循环打印时都会打印垃圾?”。我也很想知道我遇到的错误的详细信息。

代码是

#include <stdio.h>
void main() 
{
    int k = 3, n = 5, i = 0, j = n;
    int LA[] = {1,3,5,7,8};
    printf("The original array elements are :\n");
    for(i = 0; i<n; i++) {
        printf("%d ",LA[i]);
    }
    n = n + 1;
    while( j >= k){
        LA[j+1] = LA[j];
        j = j - 1;
    }
    LA[k] = 10;
    printf("\nThe array elements after insertion1 :\n");
    for(i = 0; i<n; i++) {
        printf("%d ",LA[i]);
    }
    n = n + 1;
    while( j >= k){
        LA[j+1] = LA[j];
        j = j - 1;
    }
    LA[k] = 20;
    printf("\nThe array elements after insertion2 :\n");
    for(i = 0; i<n; i++) {
        printf("%d ",LA[i]);
    }
    n = n + 1;
    while( j >= k){
        LA[j+1] = LA[j];
        j = j - 1;
    }
    LA[k] = 30;
    printf("\nThe array elements after insertion3 :\n");
    for(i = 0; i<n; i++) {
        printf("%d ",LA[i]);
    }
}

输出是

The original array elements are :
1 3 5 7 8 
The array elements after insertion1 :
1 3 5 10 7 8 
The array elements after insertion2 :
1 3 5 20 7 8 2087809280 
The array elements after insertion3 :
*** stack smashing detected ***: ./a.out terminated
1 3 5 30 7 8 2087809280 -1077687568 Aborted (core dumped)

感谢您的宝贵时间。

最佳答案

你声明了一个大小为 5 的数组 LA。

 int LA[] = {1,3,5,7,8};

稍后,您的代码尝试添加其他元素,但是 LA 的大小仍然是 5,因此您将值放在您尚未分配的数组空间中。

那么有可能,数组是在堆栈上分配的,并且由于您正在写入不属于数组的区域,所以您弄乱了堆栈。

任何 printf 访问超出 LA 大小的索引都将是内存中该位置的任何内容

关于arrays - "*** stack smashing detected ***: ./a.out terminated Aborted (core dumped)"- 数组插入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44550345/

相关文章:

javascript - 重命名对象的不定嵌套数组中的属性

c++ - C++中如何匹配两个数组的内容

algorithm - 插入排序运行时复杂度的最佳描述是什么

c - 二叉搜索树插入不起作用

javascript - 在这种情况下有没有更好的方法来使用过滤器数组?

javascript - Lodash:提取属性、分割数组、获取唯一值

java - Java 中传递给方法的数组 - 这里传递了什么?值(value)还是引用?

c++ - 以当前节点为根的二进制搜索树插入 C++

c++ - 进行少量插入时应该使用哪个 STL 容器?

qt - QTreeView&QAbstractItemModel&insertRow