向数组存储double值时触发Core dumped错误排查求助
数组越界导致Core Dumped问题排查与修复
我使用了max_size为10的数组,当输入的数值数量超过数组大小时,程序会返回包含异常值的数组,执行排序后触发“Core dumped”错误。我认为自己的函数没有越界问题,以下是数组存储、排序及打印的函数代码,请求帮助排查问题:
void store_array(int argc, char *argv[], double arr[], int max_size){ if (argc<2){ printf("If you wish to store values in the array, enter them after the program command!\n"); } int i; for (i = 1; i < argc && i <= max_size; i++) { arr[i-1] = atof(argv[i]); } if (argc - 1 > max_size){ printf("Sorry, but this function can only store %d values. The rest of the values weren't used.", max_size); } } // Function to sort the array void sort_arrays(double array[], int array_size){ int step, i; double tmp; for (step = 0; step < array_size-1; step++){ for (i=0; i < array_size - step - 1; i++){ if (array[i] > array[i+1]){ tmp = array[i]; array[i] = array[i+1]; array[i+1] = tmp; } } } return; } // Function to print the array void print_double_array(double a2[], int num_entries){ int i; for (i = 0; i < num_entries; i++) { printf("%.2f\n", a2[i]); } }
问题根源分析
- 有效元素数量传递错误:
store_array最多存储max_size个元素,但你调用sort_arrays和print_double_array时,大概率传入了argc-1(所有输入参数的总数),而非实际存入数组的有效元素数(最多10个)。当输入超过10个值时,排序/打印函数会访问数组中未初始化的内存,甚至越界访问数组外的区域,直接触发段错误(Core dumped)。 - 未初始化元素干扰:数组中未被赋值的元素是垃圾值,即使没有越界,排序时也会把这些异常值纳入计算,导致结果出现异常值。
修复方案
- 修改
store_array函数,让它返回实际存储的元素数量,这样调用者能明确知道数组中有效元素的范围。 - 调用排序和打印函数时,传入这个实际有效元素数,确保只处理已经正确赋值的元素。
修复后的完整代码
#include <stdio.h> #include <stdlib.h> // 修改为返回实际存储的元素数量 int store_array(int argc, char *argv[], double arr[], int max_size){ if (argc < 2){ printf("If you wish to store values in the array, enter them after the program command!\n"); return 0; } int i; int count = 0; for (i = 1; i < argc && i <= max_size; i++) { arr[i-1] = atof(argv[i]); count++; } if (argc - 1 > max_size){ printf("Sorry, but this function can only store %d values. The rest of the values weren't used.\n", max_size); } return count; } // 排序数组 void sort_arrays(double array[], int array_size){ int step, i; double tmp; for (step = 0; step < array_size-1; step++){ for (i=0; i < array_size - step - 1; i++){ if (array[i] > array[i+1]){ tmp = array[i]; array[i] = array[i+1]; array[i+1] = tmp; } } } } // 打印数组 void print_double_array(double a2[], int num_entries){ int i; for (i = 0; i < num_entries; i++) { printf("%.2f\n", a2[i]); } } // 示例主函数 int main(int argc, char *argv[]) { const int MAX_SIZE = 10; double arr[MAX_SIZE]; int actual_count = store_array(argc, argv, arr, MAX_SIZE); if (actual_count > 0) { sort_arrays(arr, actual_count); print_double_array(arr, actual_count); } return 0; }
修复说明
store_array新增返回值,记录实际存入数组的元素个数,让后续函数能精准控制操作范围。- 主函数中用
actual_count作为排序和打印的参数,彻底避免访问未初始化或越界的内存。 - 给提示信息添加换行符
\n,避免输出内容黏连混乱。
内容的提问来源于stack exchange,提问作者wayzfut
相关产品推荐
相关产品推荐

