0

I am working in visual studio 2010 and I received a project where the original programmer did this about half the time inside functions and methods

    TCHAR some_local_variable[size] = {0};

and the other half of the time, he did not initialize the array:

    TCHAR some_local_variable[size];

I am well aware of what the first assignment does, but I was wondering if the MSVC compiler guarantees a null character at index 0 in the second case. I did test this out and the first character was set to 0 followed by garbage as expected, but I am not sure if this is guaranteed or not?

Secondly, even if a null character is guaranteed (or if it isn't, simply setting the first character to 0), is there any good reason to initialize the entire array with 0s, especially when I always do the following after any string manipulation:

    some_local_variable[size-1] = 0;

My only thought is there could be a problem if the function manipulating the string did not null terminate AND the number of characters copied were less than size-1. For example, if it copied size-5 characters and did not null terminate, my termination at size-1 would potentially expose garbage in size-4 to size-2. However, I don't think is a problem with the majority of standard library or Win32 functions.

Paul
  • 265
  • 1
  • 2
  • 10
  • The problem here is the use of terrible C arrays and magic fixed-size buffers. – Puppy Aug 25 '15 at 22:35
  • @Puppy Unfortunately, sometimes that is what is required. – Paul Aug 25 '15 at 22:38
  • @Paul not often. In C++, you can use vector. If heap allocation is a problem, you can use an array-backed pseudo-vector, or a vector with a fancy stack-backed allocator, so up to a certain size it is on the stack, and past that it heap allocates. – Yakk - Adam Nevraumont Aug 26 '15 at 01:07
  • @Yakk That may be so, but it is irrelevant in the context of this question ... heap allocated memory has to be initialized, too. On a side note, there are still many cases where fixed buffers are preferable. For example, in this case, the string sizes are relatively small, have a known max, and are typically within +- 10 characters. A fixed buffer is appropriate. – Paul Aug 26 '15 at 06:59

1 Answers1

1

No, it doesn't. Uninitialized memory locations have random contents. (Debug builds may do some initialization to help detect memory corruption but that doesn't happen in release builds.)

You should not rely on any memory contents unless you explicitly initialized that memory region to some known value.

This question has details about the memory initialization for debug builds. (I'm not sure if the listings are complete.)

Community
  • 1
  • 1
xxbbcc
  • 16,930
  • 5
  • 50
  • 83
  • That is what I thought, but the weird thing is, even in Release builds, when I print out an uninitialized TCHAR array, the first character is always set to 0. However, I will be sure not to trust this as guaranteed. Thank you! – Paul Aug 25 '15 at 22:43