cmallocdynamic-memory-allocationrealloccalloc

C dynamic memory allocation


I am learning C but I am still a noob. I am writing a program as an exercise on dynamic memory allocation that takes text from the user with unknown length and gives back this text with no spaces, tabs, special characters or numbers. The program seems to work fine except that some of the text seems to be changed to unknown characters for unknown reasons. Here is the code:

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

int main()
{
    char *pstring;
    pstring = (char *)malloc( sizeof(char));

    char c = '$';

    int i = 0;
    while(c != '\n')
    {
        c = getchar();
        if(isalpha(c))
        {
            pstring[i] = c;
            realloc(pstring, (i+2)*sizeof(char));
            i++;
        }
    }

    int j;
    for(j = 0; j < i; j++)
    {
        printf("%c", pstring[j]);
    }

    return 0;
}

Working fine: enter image description here

The problem is: enter image description here


Solution

  • The realloc function can extend the existing memory, but it might as well (and probably most of the time do) allocate completely new memory. It returns the memory it has reallocated, and you don't use that returned pointer.

    Also, if realloc fails then it will return NULL, so don't assign the returned pointer to the variable you use in the realloc call, or you will loose the original pointer. Use a temporary variable, and check for NULL, then reassign to the actual pointer variable.

    On an unrelated note, sizeof(char) is specified to always be 1.


    Lastly a word of warning. The way you handle the "string" right now works fine (after fixing the problem you have now or course), but if you want to treat the data as a "proper" C string, you need to allocate one extra character, because C strings are terminated by a null character, '\0' (not to be confused with a null pointer, NULL).

    If your string doesn't have this terminator, using any standard string function will lead to undefined behavior as it will most likely go out of bounds of the allocated memory.