I'm trying to read from a file and put pointers of each line to a double pointer "stack" but always fail to realloc it. Maybe I should use a triple pointer????
int i = 1;
char * line = malloc(BUFSIZ);
char ** stack;
stack = (char ** ) malloc(sizeof(char * ));
while (fgets(line, BUFSIZ, file) != NULL) {
stack = & line;
printf("//%s", line);
printf("??%s", * stack);
i++;
stack = (char ** ) realloc(stack, sizeof(char * ) * i);
}
You get this error message because you set stack
to the address of line
. As a consequence, stack
is no more an allocated block.
There are a few errors in your code.
i
Here is the corrected code:
int i = 0; // number of line pointers in the stack
char *line = malloc(BUFSIZ);
char **stack = malloc(sizeof(char*));
while( fgets(line, BUFSIZ, file) != NULL) {
stack[i] = line;
printf("//%s", line);
printf("??%s", stack[i]);
i++;
line = malloc(BUFSIZ); // allocate a new block for the next line
stack = realloc(stack, sizeof(char*)*(i+1)); // make room for the next line
}
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.