Unexpected behavior of linux specific getline() function in C
0
votes
1
answer
191
views
#include
#include
#define MAXLEN 1024
void reverse(FILE *, FILE *);
int main(int argc, char ** argv)
{
...
reverse(fptr, stdout);
...
return 0;
}
void reverse(FILE * instream, FILE * outstream)
{
char ** buf;
char * lbuf;
int counter, i;
size_t slen;
counter = 0;
buf = malloc(MAXLEN * sizeof(char));
if (buf == NULL)
{
fputs("malloc failed\n", stderr);
exit(EXIT_FAILURE);
}
lbuf = NULL;
while ((counter = 0; i--)
{
fputs(buf[i], outstream);
free(buf[i]);
}
free(buf);
}
I have written this function to print a file in reverse order like
Hello World
How are you ?
what are you doing ?
output should look like this
what are you doing ?
How are you ?
Hello World
But there is unexpected behavior. I am using Linux specific stdio
function getline()
to scan arbitrary long line.
The problem is that if the value of MAXLEN
is 4, 5, 6, ... like this the program is giving double free or corrupt address error abort()
particularly the free()
function while printing the output.
I looked into the address returned by the geline()
function it seems that
after like 4 iterations the address of the first buffer returned by the getline()
is getting corrupted. If the MAXLEN
is 2 or big enough like 1024 the problem doesn't happen.
**Sample input** which I took
When to the sessions of sweet silent thought
I summon up remembrance of things past,
I sigh the lack of many a thing I sought,
And with old woes new wail my dear time's waste:
Then can I drown an eye, unused to flow,
For precious friends hid in death's dateless night
And weep afresh love's long since cancell's woe,
Asked by arka
(253 rep)
Nov 13, 2022, 06:51 PM
Last activity: Nov 14, 2022, 10:05 AM
Last activity: Nov 14, 2022, 10:05 AM