There are many mistakes in your program.
For starters you are passing to the function an uninitialized pointer
char *buf;
char *input = read_line(buf, 128);
In fact there is no sense to pass the pointer value of which is not used in the function.
Within the function the variable c should be declared as having the type int.
int c;
Otherwise if the type char behaves as the type unsigned char (it depends on a compiler option) a comparison it with EOF
will always evaluates to false.
Within the function the array tempBuf is not initialized. So this if statement
if (tempBuf[pos] == EOF || tempBuf[pos] == '\n') {
invokes undefined behavior.
Within the wjile llop you have to check that the value of pos
is less than the value of sz
.
The function returns a pointer to a local array that makes the returned pointer invalid.
buf = tempBuf;
return buf;
Moreover the array even does not contain a string because the terminating zero is not appended to the array.
The function should allocate dynamically memory and return pointer to the allocated memory that will contain a zero terminated string.
Below there is a demonstrative program that shows how the function can be written.
#include <stdio.h>
#include <stdlib.h>
char * read_line( size_t n )
{
char *s = malloc( n );
if ( s != NULL )
{
int c;
printf( "> " );
size_t i = 0;
for ( ; i + 1 < n && ( c = getchar() ) != EOF && c != '\n'; i++ )
{
s[i] = c;
}
s[i] = '\0';
}
return s;
}
int main(void)
{
size_t n = 128;
char *input = read_line( n );
if ( input != NULL ) printf( "Here: %s\n", input );
free( input );
return 0;
}
the program output might look like
> Hello Jake Jackson
Here: Hello Jake Jackson