This works, but here are some notes to keep in mind:
You don't even need
calloc()
-fgets()
NUL-terminates the string.Even better, use a
static
array.Don't use global variables. Declare
str
withstatic
storage duration instead.Instead of 256, use
LINE_MAX
- how come a line can only be shorter than 256 characters?getline()
is the name of a function in the POSIX C library. Rename your function to avoid name collision.Check if
malloc()
failed!Don't forget to
free()
the return value of the function after having read the last line if you use the approach with dynamic memory management.The check for the newline ending can be simplified like this:
char *p = strchr(str, '\n');
if (p)
*p = 0;
All in all, the function I would write is something like this:
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <limits.h>
char *my_getline_stdin()
{
static char buf[LINE_MAX];
if (fgets(buf, sizeof(buf), stdin)) {
char *p = strchr(buf, '\n');
if (p)
*p = 0;
return buf;
}
return NULL;
}