1

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.

3
  • new operator does not guarantee the memory block's bytes will be _zero_ed. Commented Aug 13, 2012 at 21:38
  • To initialize the data use output = new char[i+1](); Commented Aug 13, 2012 at 21:51
  • possible duplicate of C++ strlen(ch) and sizeof(ch) strlen Commented Aug 13, 2012 at 22:02

3 Answers 3

7

The newly allocated memory pointed to by output is not initialized: it may have any contents.

strlen requires its argument to be a pointer to a null-terminated string, which output is not, because it hasn't been initialized. The call strlen(output) causes your program to exhibit undefined behavior because it reads this uninitialized memory. Any result is possible.

Sign up to request clarification or add additional context in comments.

2 Comments

So, I assume output will still have the right memory size, despite strlen's undefined behavior?
output will point to an array of i + 1 char objects, yes. The strlen function does not compute the size of an array, it computes the length of a null-terminated string
0

strlen expects to find NULL at the end of the string, it counts all the caracters until it finds a 0
you should change the line to output = new char[i+1](); to initialize the chars to 0

Comments

0

In C, strings are null terminated. strlen() returns the bytes counted until that null termination is found.

new operator does not guarantee the memory block's bytes will be _zero_ed.

You could use calloc(), which zero'es all the bytes of the block it allocates, or you need to do memset(output, 0, i+1) after allocating with new operator.

2 Comments

Lets not resort to C voodoo in a C++ question. You can initialize with new using: output = new char[i+1]();
Yeah, did not think of using an empty constructor, yet, strlen() is in <cstring>.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.