Answer the question
In order to leave comments, you need to log in
Why does segmentation error occur and how to avoid it?
All good and warm! I am doing a study assignment. It is necessary to implement the Get next line functionality and the ability to accept a buffer parameter. A simple idea came to my mind, to read data from a file, until we meet a new line transfer or we meet the end of the line, we will read the length of the buffer, hammering into the line. We form the string in advance using malloc according to the length of the buffer + 1 character at the end of the string. The problem arose in that when reading the order of digits when the end of the line is reached, I stumble upon a Segmentation fault.
For example, there is a line 12345. I pass 3 to the buffer, and make two function calls, as a result I get a formatting of the line
123
Segmentation fault.
I can't understand why. so... (Please tell me.
char *get_next_line(int fd)
{
char *line;
int read_byte;
char rwrite;
long long int i;
i = 0;
line = (char *)malloc(sizeof(char) * (BUFFER_SIZE + 1));
if (!line)
return (NULL);
while (i != BUFFER_SIZE)
{
read_byte = read(fd, &rwrite, 1);
if (read_byte && rwrite)
{
if (rwrite != '\n' && rwrite != '\0')
line[i] = rwrite;
else
{
line[i] = '\0';
return (line);
}
}
else if (read_byte <= 0)
return (NULL);
i++;
}
line[i] = '\0';
return (line);
}
Answer the question
In order to leave comments, you need to log in
For a long time I could not understand what was wrong. (alas, there is no compiler at hand)
In general, purely "by eye", if I did not make a mistake anywhere:
If you make two calls with a buffer of size 3. (and the real length of the string is 5), then the second call your function will return NULL to you and you ( probably) you don’t check it anywhere (check just in case that I’m not mistaken here)
Let me explain - if the buffer is longer than the file, then you are faced with the fact that there is nothing more to read i.e. when reading 0 bytes (and you will read exactly 0 of them if the file is over) return NULL instead of returning what you could read or do something else
And, by the way, you allow a leak - you allocated memory under line, but in case of an error, don't clear it and don't return it anywhere.
cm.https://man7.org/linux/man-pages/man2/read.2.html
Well, let's omit the moment that your line will be split into several if it does not fit into the specified buffer size.
As an option, read the line until it ends, call realloc as the buffer is exhausted (for example, with a step in BUFFER_SIZE). If the buffer is slightly larger than the received string, this is not a tragedy (again, if suddenly all the same a tragedy - realloc will help).
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question