Change this:
buffer = (char*)malloc(s);
To this:
buffer = (char*)malloc(s+1);
buffer[s] = 0;
And return buffer
after you close the file; the rest of the code is redundant. In addition to that, don't forget to free
the memory pointed by buffer
at some later point in the execution of your program.
The purpose of buffer[s] = 0
is for you to be able to pass it to string functions. A few examples:
printf("%s",buffer);
strcpy(buffer2,buffer);
strcat(buffer2,buffer);
if (strcmp(buffer2,buffer) == 0) ...
Even if you're not interested in that, you still need a method with which you can detect the end of the string which is stored in the memory pointed by buffer
. The answer above suggests the method of setting buffer[s]
to a 0 (null) character. Alternatively, you can simply use the value of s
itself. However, if you choose this method, then you'll have to maintain both buffer
and s
in a structure.