ARistich
ARistich

Reputation: 3

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;
}

Upvotes: 0

Views: 1517

Answers (2)

sjsam
sjsam

Reputation: 21965

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.

Upvotes: 0

user2736738
user2736738

Reputation: 30926

Well before using strcat make

text[0]=0;

strcat expects null terminated char array for the first argument also.

From standard 7.24.3.1

  #include <string.h>
          char *strcat(char * restrict s1,
               const char * restrict s2);

The strcat function appends a copy of the string pointed to by s2 (including the terminating null character) to the end of the string pointed to by s1. The initial character of s2 overwrites the null character at the end of s1.

How do you think strcat will know where the first string ends if you don't put a \0 in s1.

Also don't forget to allocate an extra byte for the \0 character. Otherwise you are writing past what you have allocated for. This is again undefined behavior.

And earlier you had undefined behavior.

Note:

  • You should check the return value of malloc to know whether the malloc invocation was successful or not.

  • Casting the return value of malloc is not needed. Conversion from void* to relevant pointer is done implicitly in this case.

  • strlen returns size_t not int. printf("%zu",strlen(text))

Upvotes: 3

Related Questions