Why is my simple C program displaying garbage to stdout?

后端 未结 5 1517
你的背包
你的背包 2020-12-06 11:38

Consider the following simple C program that read a file into a buffer and displays that buffer to the console:

#include

main()
{
  FILE *fil         


        
5条回答
  •  佛祖请我去吃肉
    2020-12-06 12:17

    You can use calloc instead of malloc to allocate memory that is already initialised. calloc takes on extra argument. It's useful for allocating arrays; the first parameter of calloc indicates the number of elements in the array that you would like to allocate memory for, and the second argument is the size of each element. Since the size of a char is always 1, we can just pass 1 as the second argument:

     buffer = calloc (fileLen + 1, 1);
    

    In C, there is no need to cast the return value of malloc or calloc. The above will ensure that the string will be null terminated even if the reading of file ended prematurely for whatever reason. calloc does take longer than malloc because it has to zero out all the memory you asked for before giving it to you.

提交回复
热议问题