【发布时间】:2015-11-08 08:14:21
【问题描述】:
===========================
代码(文件名为test.c)
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main(int argc, char * argv[] ) {
int i=0, num=atoi(argv[1]);
char **arr=(char**)malloc(num*sizeof(char*));
FILE *fp = fopen("test.txt","r");
if( arr == NULL) { printf("out of memory\n"); exit(1); }
if( fp == NULL) { printf("cannot open the file \n"); exit(1); }
for(i=0; i< num; i++) fscanf(fp,"%s", arr+i ); // HERE
printf("%s\n", arr+num-1 );
fclose(fp);
free(arr);
return 0;
}
========
test.txt
watermelon
grape
strawberries
orange
peach
banana
mango
cherry
pineapple
apple
blueberry
raspberry
pear
melon
greengrapes
tangerine
kiwifruit
pomegranate
plum
nectarine
========
问题
当我执行了几次以下
test 1
test 2
...
...
test 7
test 8
它经常压碎诸如“核心转储”之类的东西,但按我的预期工作。
但是,当我输入高于 9 时,它永远不会崩溃...
test 9
test 10
...
是什么导致这段代码崩溃?
【问题讨论】:
-
仅供参考:如果您的代码实际上破坏了某些东西,那么您需要担心的事情更多。你想要的词是 crash ;)
-
我很抱歉暗恋,我的意思是崩溃,
-
@alexparkjw 那你为什么不修呢?
标签: c pointers malloc scanf coredump