C++ array of fixed size getting garbage values

  • A+

I was trying to rotate a string circularly by 1 shift. Here's the simple code:

#include <bits/stdc++.h> using namespace std;  int main() {   string s = "1010";   char a[s.length()];   for (int i = 0; i < s.length() - 1; i++) {     a[i] = s[i+1];   }   a[s.length()-1] = s[0];   std::cout << a << '/n';   std::cout << strlen(a) << '/n'; } 

When I run this code, I get the following output:

aditya@aditya-Inspiron-3558:~/miscCodes$ ./a.out  0101� 6 

How's my array's length is changing? And due to garbage values?


Variable Length Arrays (VLA) are not part of Standard C++. Read more in Why aren't variable-length arrays part of the C++ standard?

But let's say, that you use a compiler extension that allows them, then the problem is that you use a C function here:

std::cout << strlen(a) << '/n'; 

which expects a C string, which means a NULL-terminated string.

That means that you should make your array big enough to hold the NULL termination character, like this:

char a[s.length() + 1]; 

since string::length() will return 4 for the string "1010". That means that the C string should be this: "1010/0", i.e. the actual string, appended with the NULL terminating character. As a result, you would need an array of size 5 to store that string.

An easy fix would be:

char a[s.length() + 1] = {0}; 

which will NULL initialize every cell of the array. Then you will overwrite every cell of it with characters, except from the last cell, specially reserved for the NULL terminator.

Another approach would be to only assign the NULL terminator to the last cell of your string, like a[s.length()] = '/0';. Notice how s.length() now is the index to the last element of your array.

Standard C string functions (like strlen()) depend on the NULL termination character to mark the end of the string. In the absence of that important character, they do not know when to stop, thus accessing memory beyond from the point they are meant to visit.

That invokes Undefined Behavior (UB), which, in your computer, is accessing memory with garbage values.


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: