【发布时间】:2022-01-26 15:55:46
【问题描述】:
我正在制作一个程序,它可以根据用户输入创建一个数组并将其保存在 csv 文件中。然后用户可以对存储的数组执行矩阵和向量运算。当我开始使用 csv 文件(最初在 clion 上)时,我开始收到错误消息:“进程以退出代码 139 完成(被信号 11 中断:SIGSEGV)”调试后我发现错误“EXC_BAD_ACCESS(代码=2,地址=0x7ff7b202dff8 )”。但是,该程序在重新运行时仍然有效。可悲的是,尽管在我写了第 60 -65 行以便每次运行该函数时都制作一个不同的 csv 文件后,我开始在重新启动时收到错误:“信号:分段错误(核心转储)”。什么可能导致这些错误?这是我的 replit 代码:
“https://replit.com/@iasonaszak/the-matrix#main.c”
提前感谢您的帮助!!
这是我的代码:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "time.h"
#include <math.h>
#include <stdbool.h>
int a;
char c[20];
int num;
bool b = true;
int main() {
while (b ==true){
void create_array();
void delete_array();
int user_answer;
time_t t;
srand((unsigned) time(&t));
printf(
" 1.create an array\n 2.load an array\n 3.Show available arrays\n 4.Delete array\n 5.Vector operations \n 6.Matrix operations"
) ;
printf("Please choose one of the following options!\n");
scanf("%d" , &user_answer);
if (user_answer == 1){
create_array( );
}
else if (user_answer == 4){
delete_array();
}
return 0;
}
}
void create_array(){
int rows;
int cols;
int i;
int j;
int matrix[i][j];
printf("how many columns would you like your array to have");
scanf("%d" ,&cols );
printf("how many rows would you like your array to have");
scanf("%d" ,&rows );
char filename[80];
FILE *fout = fopen(filename, "wt");
FILE *last = fopen("lastnum.csv" , "w");
fgets(c , 20 , last);
num = atoi(c);
snprintf(filename, sizeof(filename), "prefix.%d.csv", num);
for (i = 0 ; i < rows; i ++){
printf("\n");
fprintf(fout , "\n");
for (j = 0 ; j < cols; j ++){
scanf("%d", &matrix[i][j]);
char str[(int)((ceil(log10(matrix[i][j]))+1)*sizeof(char))];
sprintf(str , "%d " , matrix[i][j]);
fprintf(fout ,"%s" , str);
}
}
printf("Your array was saved successfuly inside a csv file");
num++;
}
void delete_array(){
remove("prefix.0.csv");
remove("prefix.1.csv");
remove("prefix.2.csv");
remove("prefix.3.csv");
remove("prefix.4.csv");
remove("prefix.5.csv");
remove("prefix.6.csv");
remove("prefix.7.csv");
remove("prefix.8.csv");
remove("prefix.9.csv");
printf("all arrays were deleted");
}
void preview_arrays(){
FILE *F0 = fopen("prefix.0.csv" , "r");
}
【问题讨论】:
-
请内联导致此问题的代码,而不是链接到它。
-
好吧抱歉我编辑了问题
-
谢谢。我现在建议您将代码编辑为可读(适当的缩进和空格使用)。这样做会使调试更容易。
-
您是否在调试器中单步执行代码 段错误是由于某些内存溢出,所以您可能超出了缓冲区大小或类似大小。
-
remove是如何定义的? 提示:分段错误通常是由于分配和释放内存的问题或超出范围的数组访问而发生的。