I want to make a function that create a new string with a specific lenght. This is the code:
char* newString(int lenght){
char* newstring =(char*)((calloc(lenght, sizeof(char))));
newstring[lenght] = '\0';
return newstring;
}
I use it in this way:
char* string = newString(10);
My problem is that when I do:
printf("String lenght %lu \n",strlen(string));
I get 0 but I don't understand why. I am neophyte with C. Thank for your time
calloczero initializes your array, and you never populate it with anything. Also, it's spelled "length"t[lenght] = '\0'regardless, thus invoking undefined behavior. Arrays in C are zero-base-indexed. Meaning0...(lenght-1)are the allowable range of indexes..t[length] = '\0';is an out of bound write.