【问题标题】:"*** stack smashing detected ***: ./a.out terminated Aborted (core dumped)" - array insertion“***检测到堆栈粉碎***:./a.out 终止中止(核心转储)” - 数组插入
【发布时间】:2017-11-16 22:26:07
【问题描述】:

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

代码是

#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)

感谢您的宝贵时间。

【问题讨论】:

  • 错误的详细信息是您损坏了堆栈。查找“为了乐趣和利润而粉碎堆栈”。 (免责声明:我还没有阅读代码)

标签: arrays insertion


【解决方案1】:

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

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

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

那么很有可能,数组被分配在堆栈上,并且由于您正在写入不属于数组的区域,因此您将堆栈弄乱了。

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

【讨论】:

  • 我认为程序仅在第一个 while 循环期间注销数组的末尾。然后,他只是从数组末尾格式化 printf 。然后 main 尝试退出并意识到堆栈已损坏(尽管只有四个字节)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-26
  • 1970-01-01
  • 2021-07-18
  • 1970-01-01
  • 2021-10-10
  • 1970-01-01
相关资源
最近更新 更多