Baja
Baja

Reputation: 55

Problem with c with dynamically allocating an array

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

void input_all(char* array)
{
    int c = 0;
    int increse = 20;
    int number_of_char = 0;

    for (int increment = 0; (c = getchar()) != '\n'; increment++)
    {
        ++number_of_char;
        if (number_of_char % 10)
        {
            array = (char*)realloc(array, increse + sizeof(char));
            if (array == NULL)
            {
                printf("not alocated!");
                exit(22);
            }
            increse += 10;
        }

        array[increment] = c;
    }
    printf("%s\n", array);
}

int main(void)
{
    char* array = (char*)malloc(10);
    if (array == NULL)
    {
        printf("not alocated\n");
        exit(33);
    }
    input_all(array);

    printf("%s\n", array);
    return 0;
}

So what I'am trying to do is to fill up "array" with getchar. When I try to print it out I get some garbage values at the end (most of the time). I think the problem is that I'am giving out to much space to "array" with realloc but I have no idea how to fix it. I also tried placing all the sizes to 1 in malloc and realloc and increse so that whenever i get a charcter the size of "array" increses but it still did not work. Anyone have any idea how ot fix it? Thanks in advance!

Upvotes: 0

Views: 63

Answers (1)

Barmak Shemirani
Barmak Shemirani

Reputation: 31679

array must be null terminated, otherwise printf and other c-string functions don't know where the end of the string is at.

realloc may not return the same address (although that's not an issue on your PC), you have to use the address of pointer.

You can allocate the whole array realloc. If subsequent realloc fails then you don't necessarily have to exit, you can print error and return the string which was already allocated.

void input_all(char** parray)
{
    char* arr = NULL;
    int size = 0, i = 0;
    while(1)
    {
        int c = fgetc(stdin);
        if (c == '\n' || c == EOF)
            break;
        if (i == size)
        {
            size += 10;
            char* temp = realloc(arr, size + 1);
            if (temp == NULL) { printf("realloc failed\n"); break; }
            arr = temp;
        }
        arr[i++] = (char)c;
    }
    if(arr)
        arr[i] = '\0'; //<- don't forget to terminate the string with 0
    *parray = arr;
}

int main(void)
{
    char* array = NULL;
    input_all(&array);
    if (!array)
        return 1;
    printf("%s\n", array);
    free(array);
    return 0;
}

Upvotes: 1

Related Questions