0

Please can someone tell me why the code bellow make dev c++ crashes ?

FILE* input;
int k=0;
char filename[]="";
int* Tab=NULL;
printf("Please specify the filename you want to open and read\n");

  scanf("%s",&filename);

//strcat(filename,".txt");
input=fopen(filename,"r");
if(input==NULL)
{
    printf("File open error");
  }

fscanf(input,"%d",&total);
Tab=malloc(total);
for(k=0;k<total;k++)// here is my problem 
{
    fscanf(input,"%d",&Tab[k]);
  }

The file gets open normally and the read was correct at first atempt then it sddenly started crashing . the variable total can be read as well the next for loop is the problem .

Any help Please ?

Jean Ouédraogo
  • 234
  • 2
  • 6
  • 16

1 Answers1

2

So the comments all show one thing: you think the compiler will handle memory for you.

Not so! In C, all memory handling must be done by you:

  • in char filename[]=""; you declare a 1-byte array (only the '\0') but you think that the scanf("%s",&filename); will magically increase that to be able to hold a much longer filename. Not so! (And why the & on a character array?)

  • in Tab=malloc(total); you think the compiler knows the size of the elements you want to store in Tab. Not so!

With every comment, you make a small change and "Darn! It still doesn't work!" Of course not, as you did not understand that the C compiler does not do memory handling for you. I suggest you read the book again on memory: read about global, static and automatic variables; read about arrays and strings and read about malloc, realloc and free.

(This is more a comment than a solution)

Paul Ogilvie
  • 25,048
  • 4
  • 23
  • 41