Search code examples
cpointersmallocallocationrealloc

Char Pointer Malloc/Realloc


What I'm trying to do is a small program that takes a suite of numbers (123654000256 per example) and deletes all the numbers after detecting a '0' (should return 123 if I enter 1230456), so I'm trying to do it with malloc / realloc but when I realloc it still returns all the elements

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

/* run this program using the console pauser or add your own getch, system("pause") or input loop */

int main(int argc, char *argv[]) {
    char *suite;
    int i,a,temp;

    suite = (char*)malloc(100*sizeof(char));
    printf("Enter a suite of numbers : ");
    scanf("%s",suite);

    i=-1;
    do{
        i++;
        a=i;
    }while((suite[i]-'0') != 0);

    suite = realloc(suite,a*sizeof(char));
    printf("New suite: ");
    printf(suite);

    return 0;
}

I enter 4564560123 it returns it as I entered it, whats the prob ?


Solution

  • You need to realloc space for a + 1 to fit the null terminator, then null terminate the string, suite[a] = '\0'.


    Why this bug gave you the whole sequence of numbers:

    Once you call realloc, it just means that the system is free to use the remaining parts of the previously allocated memory for other purposes. There is no such thing as "deleting" memory, it just gets invalidated and the old data will remain in those memory cells until used for other purposes.

    So if you forget null termination and the system has not yet used that memory, the old data remains there and that's why you get the full sequence as output. There is no guarantee that you would get the old data though - the program could as well crash.