我正在读取文件
((标记为in1的文件内容:]
8
0 2 1 4 2 2 3 1
3 2 5 4 6 7 9 2 8
通过命令行传递到我的程序。
((这里是最低工作版本):
/*
*Run using make with accompanying Makefile using file in1 as input on command line
*
* */
#include<stdio.h>
#include<stdlib.h>
int main(int argc, char* argv[]){
if(argc != 2){
fprintf(stderr,
"Error: Improper amount of command line arguments. Need one input file.\n");
exit(EXIT_FAILURE);
}
FILE* fp = fopen(argv[1], "r");
int n;
int* A = calloc(n+1, sizeof(int));
int* idx = calloc(n, sizeof(int));
fscanf(fp, "%d", &n); //assigns n from file
printf("N is equal to : %d\n", n);
for(int i = 0; i < n; i++){ //assigns operations from file
fscanf(fp, "%d", &idx[i]);
}
for(int i = 0; i < n; i++){
printf("idx[%d] = %d\n", i, idx[i]);
}
for(int i = 0; i <= n; i++){//set operands
fscanf(fp, "%d", &A[i]);
}
for(int i = 0; i <= n; i++){
printf("A[%d] = %d\n", i, A[i]);
}
for(int i = 0; i < n; i++){
printf("idx[%d] = %d\n", i, idx[i]);
}
}
此最小版本仍会产生相同的结果。这是输出:
N is equal to : 8
idx[0] = 0
idx[1] = 2
idx[2] = 1
idx[3] = 4
idx[4] = 2
idx[5] = 2
idx[6] = 3
idx[7] = 1
A[0] = 3
A[1] = 2
A[2] = 5
A[3] = 4
A[4] = 6
A[5] = 7
A[6] = 9
A[7] = 2
A[8] = 8
idx[0] = 8
idx[1] = 2
idx[2] = 1
idx[3] = 4
idx[4] = 2
idx[5] = 2
idx[6] = 3
idx[7] = 1
请参阅idx [0]如何首先等于0,然后在分配A之后,其值为8?
这是为什么?
(使文件运行程序):
PROGRAM_NAME = minRecreate
FLAGS = -std=c99 -Wall
SOURCE = $(PROGRAM_NAME).c
OBJECT = $(PROGRAM_NAME).o
EXEBIN = $(PROGRAM_NAME)
$(EXEBIN) : $(OBJECT)
gcc -o $(EXEBIN) $(OBJECT)
$(OBJECT) : $(SOURCE)
gcc -c $(FLAGS) $(SOURCE)
clean :
rm $(EXEBIN) $(OBJECT)
memcheck : $(EXEBIN)
valgrind --leak-check=full $(EXEBIN) in1
第一次使用n
时,未初始化。程序的其余部分导致未定义的行为,但是最有可能发生的是A
不够大,因此最终导致了idx
崩溃。