Home > Blockchain >  Infinity getchar with reallocation
Infinity getchar with reallocation

Time:10-13

hi i am a trying to make the console read characters and increase the size with realloc until i hit ctr z and end the loop.The terminal is displayng segmentation fault.The program should work like this:

f
f
f
f
f
f

Hit ctrl z print the characters. How to fix this?

#include <stdio.h>
#include <stdlib.h>


int main()
{
    int size = 2;
    char* buffer = NULL;
    buffer = (char*) malloc(size*sizeof(char));
    if(buffer==NULL)
    {
        puts("Allocation failed");
    }

    printf("Enter character: ");
    while(1)
    {
        *buffer = getchar();
        size  ;
        buffer = (char*) realloc(buffer,size*sizeof(char));
         if(buffer==NULL)
    {
        puts("Allocation failed");
    }
    }
    
    printf("%c",buffer);
    free(buffer);
    

}

CodePudding user response:

Instead of this:

buffer = getchar();

This:

*buffer = getchar();

But you should also support detecting for EOF in case of redirected input:

while(1)
{
    int result = getchar();
    if (result == EOF)
    {
        break;
    }
    *buffer = (char)result;

CodePudding user response:

You're struggling with this. It's important to note that realloc( NULL ... acts just like malloc(), so you can "grow" the array from zero as needed calling realloc from just one location.

#include <stdio.h>
#include <stdlib.h>

int main() {
    int ch, size = 0; // trust me
    char *buffer = NULL;

    printf( "Enter characters: " );
    while( ( ch = getchar() ) != EOF ) {
        char *tmp = (char*)realloc( buffer, (size 1) * sizeof *tmp );
        if( tmp == NULL ) {
            puts( "Allocation failed" );
            exit( 1 );
        }
        buffer = tmp; // the possibly new memory address
        buffer[ size   ] = (char)ch; // the new character just entered.
    }

    // NB: buffer is NOT a null terminated C string.
    // It is an array of characters that can be printed, though.
    printf( "\nGot this: %.*s", size, buffer );
    
    return 0;
}
Enter characters: Quick Brown Foxes ^Z

Got this: Quick Brown Foxes
  •  Tags:  
  • c
  • Related