Using fgets() with char* type

后端 未结 3 901
傲寒
傲寒 2021-01-12 15:17

I have a simple question about using fgets() with char* string.

....
char *temp;
FILE fp=fopen(\"test.txt\", \"r\");

fgets(temp, 500, fp);
printf(\"%s\", te         


        
3条回答
  •  悲哀的现实
    2021-01-12 16:20

    char *temp is only a pointer. At begin it doesn't points to anything, possibly it has a random value.

    fgets() reads 500 bytes from fp to the memory addresse, where this temp pointer points! So, it can overwrite things, it can make segmentation faults, and only with a very low chance will be work relativale normally.

    But char temp[500] is a 500 bytes long array. That means, that the compiler does the allocation on the beginning of your process (or at the calling of your function). Thus this 500 bytes will be a useable 500 bytes, but it has a price: you can't reallocate, resize, free, etc. this.

    What the google wants from you, is this:

    char *temp = (char*)malloc(500);
    

    And a

    free(temp);
    

    after you don't need this any more.

提交回复
热议问题