繁体   English   中英

“检测到*** ***堆栈粉碎失败:./ a.out已终止,异常终止(核心转储)”-阵列插入

[英]“*** stack smashing detected ***: ./a.out terminated Aborted (core dumped)” - array inserion

我在互联网上通过下面的代码在数组中插入一个元素,我的问题是,数组的大小如何在第一次插入时特别增加?在每次执行循环打印时都会打印一个垃圾。获取有关我得到的错误的详细信息。

该代码是

#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,因此您将值放置在尚未分配的数组空间中。

然后,可能会在堆栈上分配该数组,并且由于您正在写入不属于数组的区域,因此会弄乱堆栈。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM