Search code examples
cpointersdynamic-memory-allocationrealloc

dynamically allocating memory to save user input in it


I'm trying to write this simple code which takes the user input message, saves it on the stack, and then shows it back to the user.

I don't want to limit the number of characters the user can type in, so I used dynamic memory allocation each time the user enters a new character.

The code runs well if the user entered a small no. of characters, but it doesn't work if the user typed in a big no. of characters

for example: if I entered "Ahmed" it will show it back to me, but if I typed something with more characters it doesn't.

this is my code:

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

int main()
{
    char *UserInput;
    UserInput=(char *)calloc(1,sizeof(char));
    int i=0,ii=0;
    printf("Enter a message! \n");
    while(*(UserInput+ii)!='\n'){
        scanf("%c",(UserInput+i));
        ii=i;
        i++;
        UserInput=realloc(UserInput,i*sizeof(char));
    }
    for(i=0;i<=ii;i++){
        printf("%c",*(UserInput+i));
    }

    return 0;
}

Solution

  • Changes to be made in your program to run properly:

    UserInput = realloc(UserInput, ((i + 1) * sizeof(char)));
    

    Explanation:

    When you are accepting input by scanf, you are taking in a sequence of characters (including '\n'). As your format specifier is %c it is supposed to take in only a single character. The input is not a single character, but a character sequence. Also %c does not filter out '\n'. The extra characters get stored into the buffer of scanf. Next time when scanf is called, it takes the input from the buffer.

    By using calloc, you are allocating the UserInput 1 byte of space in the beginning, but when you are calling scanf in each iteration the character is stored in UserInput + 1th location, which has not been allocated to your variable by calloc, but which is still in the buffer of calloc i.e. it still has not touched system memory/heap. you are reallocating your memory at end of iteration. i.e. you are using unallocated memory and after that you are allocating it to UserInput.

    For small character sequences, this will not give any errors as the buffer of calloc is not that small, but for large character sequences, you will get a error - "corrupted size vs. prev_size" - which is an indicator of heap attack/exploitation.

    This happened because the calloc buffer is now exhausted, and you are using the memory from system heap, which sends the system into frenzy. You modify memory outside the range that was allocated for you to use, and the system finds that its control data has been corrupted, and is not really happy with that.

    also don't forget to free(UserInput);

    Prost !