carraysrandomchars

random chars in dynamic char array C


I need help with char array. I want to create a n-lenght array and initialize its values, but after malloc() function the array is longer then n*sizeof(char), and the content of array isnt only chars which I assign... In array is few random chars and I dont know how to solve that... I need that part of code for one project for exam in school, and I have to finish by Sunday... Please help :P

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

int main(){

    char *text;

    int n = 10;

    int i;

    if((text = (char*) malloc((n)*sizeof(char))) == NULL){
        fprintf(stderr, "allocation error");
    }

    for(i = 0; i < n; i++){
        //text[i] = 'A';
        strcat(text,"A");
    }

    int test = strlen(text);
    printf("\n%d\n", test);

    puts(text);
    free(text);

    return 0;
}

Solution

  • To start with, you're way of using malloc in

    text = (char*) malloc((n)*sizeof(char)
    

    is not ideal. You can change that to

    text = malloc(n * sizeof *text); // Don't cast and using *text is straighforward and easy. 
    

    So the statement could be

    if(NULL == (text = (char*) malloc((n)*sizeof(char))){
        fprintf(stderr, "allocation error");
    }
    

    But the actual problem lies in

    for(i = 0; i < n; i++){
        //text[i] = 'A';
        strcat(text,"A");
    }
    

    The strcat documentation says

    dest − This is pointer to the destination array, which should contain a C string, and should be large enough to contain the concatenated resulting string.

    Just to point out that the above method is flawed, you just need to consider that the C string "A" actually contains two characters in it, A and the terminating \0(the null character). In this case, when i is n-2, you have out of bounds access or buffer overrun1. If you wanted to fill the entire text array with A, you could have done

    for(i = 0; i < n; i++){ 
        // Note for n length, you can store n-1 chars plus terminating null
        text[i]=(n-2)==i?'A':'\0'; // n-2 because, the count starts from zero
    }
    //Then print the null terminated string
    printf("Filled string : %s\n",text); // You're all good :-)
    

    Note: Use a tool like valgrind to find memory leaks & out of bound memory accesses.