For starters the code has a memory leak. At first a memory was allocated
stack = (char ** ) malloc(sizeof(char * ));
and then the pointer stack
was reassigned with the address of the pointer line
.
while (fgets(line, BUFSIZ, file) != NULL) {
stack = & line;
//…
This statement
stack = (char ** ) realloc(stack, sizeof(char * ) * i);
results in undefined behavior because the pointer stack after the statement
stack = & line;
does not point to a dynamically allocated memory. It points to a local variable line
.
It seems what you are trying to do is the following shown in the demonstrative program below. Only instead of a file there is used the standard input stream stdin
.
#include <stdio.h>
#include <stdlib.h>
#include<string.h>
int main(void)
{
char *line = malloc( BUFSIZ );
char **stack = NULL;
size_t n = 0;
while ( fgets( line,BUFSIZ, stdin ) != NULL )
{
line[strcspn( line, "\n" )] = '\0';
char **tmp = realloc( stack, ( n + 1 )* sizeof( char * ) );
if ( tmp != NULL )
{
stack = tmp;
++n;
stack[n-1] = malloc( BUFSIZ );
if ( stack[n-1] != NULL ) strcpy( stack[n-1], line );
}
}
for ( size_t i = 0; i < n; i++ )
{
if ( stack[i] != NULL ) puts( stack[i] );
}
for ( size_t i = 0; i < n; i++ )
{
free( stack[i] );
}
free( stack );
free( line );
return 0;
}
If to enter two strings
Hello
World
then the output will be
Hello
World