Search code examples
cdynamicprintfallocation

Print array with pointer in C


I have a pointer to an array of char and I need to print the entire array (not one after the other but the entire array). I have the error: zsh: segmentation fault. I don't understand why. My code take a text from stdin and put the chars in an array. If the first array char_array isn't big enough I put them in the second one called bigger_array.

int main() {
    int c;
    int index = 0;
    size_t size = 100;                        
    char *char_array = malloc(size * sizeof(char)); 
    if (char_array != 0) {
        while ((c = getchar()) != EOF && index < size) {
            char_array[index] = c;
            index++;
        }
        size_t newSize = size * 100;
        char *bigger_array = realloc(char_array, newSize * sizeof(char)); 
        if (bigger_array != 0) {
            bigger_array = char_array;
            while ((c = getchar()) != EOF && index < newSize) {
                bigger_array[index] = c;
                index++;
            }
            size = newSize;
        }
    }
    printf(*char_array);
    return 0;
}

Solution

  • There are multiple issues in your code:

    • you do not include <stdio.h> nor <stdlib.h>
    • you should free char_array and store big_array to char_array so char_array points to the bigger allocated array.
    • printf(*char_array) has undefined behavior for multiple reasons. You can print the characters with fwrite(char_array, 1, index, stdout) or with printf("%.*s\n", (int)index, char_array).
    • there is no need for separate loops, just reallocate the array on demand.

    Here is a modified version:

    #include <stdio.h>
    #include <stdlib.h>
    
    int main() {
        int c;
        size_t index = 0;
        size_t size = 100;
        char *char_array = malloc(size);
        if (char_array != NULL) {
            while ((c = getchar()) != EOF) {
                if (index == size) {
                    size_t new_size = size + size / 2 + size / 8; /* increase by the golden ratio */
                    char *new_array = realloc(char_array, new_size);
                    if (new_array == NULL) {
                        fprintf(stderr, "out of memory\n");
                        free(char_array);
                        return 1;
                    }
                    size = new_size;
                    char_array = new_array;
                }
                char_array[index++] = c;
            }
            printf("%.*s\n", (int)index, char_array);
        }
        return 0;
    }