I'm trying to read line from stdin with fgets(), I want to use fgets() in my function, which I think is the problem. The string could be max 1024 chars long. When I run this code I get "Segmentation fault (core dumped)"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_SIZE 1025
void print_fgets();
int main()
{
print_select();
return 0;
}
void print_select()
{
char *str;
int length;
while (fgets( str, MAX_SIZE, stdin)!=NULL)
{
length=strlen(str);
if (length==MAX_SIZE-1 && str[length-1]!='\n')
{
printf("Error, line overeached buffer!\n");
return 1;
}
if (str[length-1]=='\n')
str[length-1]='\0';
printf("%s\n", str);
}
}
The problem is that you try to write to the location that the
str
pointer points to. Initially it will point to some garbage address (due tochar *str
not being initialized).You can try a stack based solution instead by changing:
to:
Or if you want to allocate memory dynamically for the array, do this instead:
Don't forget things like array index starting with
0
and goes toMAX_SIZE - 1
(in your case) and NUL termination (strings must end with it).