I would like to have a dynamic character array who’s length equals the loop iteration.
char* output;
for (short i=0; i<2; i++){
output = new char[i+1];
printf("string length: %d\n",strlen(output));
delete[] output;
}
But strlen is returning 16, where I would expect it to be 1 and 2.
The newly allocated memory pointed to by
outputis not initialized: it may have any contents.strlenrequires its argument to be a pointer to a null-terminated string, whichoutputis not, because it hasn’t been initialized. The callstrlen(output)causes your program to exhibit undefined behavior because it reads this uninitialized memory. Any result is possible.