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;
}
To start with, you're way of using
mallocinis not ideal. You can change that to
So the statement could be
But the actual problem lies in
The
strcatdocumentation saysJust 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, wheniisn-2, you have out of bounds access or buffer overrun1. If you wanted to fill the entiretextarray with A, you could have doneNote: Use a tool like valgrind to find memory leaks & out of bound memory accesses.