Up until now I have basically avoided using malloc when possible and just allocate space with a static array. Lately I have been experimenting with malloc, and I ran into a problem which left me scratching my head for a bit. Here is an example of what I was trying to do originally:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void foo(char **txt_ptr)
{
enum {
BUF_MAX = 25
};
char *buffer = malloc(BUF_MAX * sizeof *buffer);
char *p;
if (buffer == NULL) {
puts("No memory for you!");
exit(EXIT_FAILURE);
}
printf("\nEnter some text: ");
fflush(stdout);
if (fgets(buffer, sizeof buffer, stdin) == NULL) {
perror("fgets()");
}
if ((p = strchr(buffer, '\n')) != NULL) {
*p = '\0';
}
*txt_ptr = buffer;
}
int main(void)
{
char *textp = NULL;
foo(&textp);
printf("\n%s\n\n", textp);
return 0;
}
This line was giving me trouble:
Code:
if (fgets(buffer, sizeof buffer, stdin) == NULL) {
IIRC, that line would work properly with a static array, but in this case, 'sizeof buffer' equals 8. Not what I wanted at all; I could enter as many characters as I wanted, but the printf in main would only print 7 of them. So I came up with a kludge that looked like this:
Code:
if (fgets(buffer, (BUF_MAX * sizeof *buffer), stdin) == NULL) {
It 'works', but I hate learning this way in case there is something wrong with it. What is the nicest way to solve this problem?