0

i have been trying to write the order in which the tree is traversed, to a .txt file in C. Instead of using arrays, i'm using my own data type vector to store the node values of the tree. I then try to create a character array from the items in the vector. This process goes as expected, however when i print the char array to the screen, it prints 5 random character in the beginning. I'm sure enough that the problem isn't in the vector but elsewhere because when i try to print the characters inside the loop, it doesn't print any unexpected characters to the screen (please see image below). Help in spotting the bug will be highly appreciated.

NODE* char_tree = optimised_tree(); // First Node of the tree
vector* tree_items = new_vector();
parse_tree(char_tree, tree_items); // parses the tree and add nodes to vector

int len = vec_size(tree_items); // size of the vector
char xs[len + 2];
char x[2];

for (int i = 0; i < len; ++i)
{
    int o = vec_get(tree_items, i); // item at index i in vector tree_items
    printf("%c ", o);
    x[0] = (char)o;
    x[1] = '\0';
    strcat(xs, x);
}

xs[len] = '\n';
xs[len + 1] = '\0';
printf("\n-> %sSIZE %lu\n", xs, sizeof(xs));

output

lag
  • 520
  • 2
  • 10
  • 26

1 Answers1

2

The problem is that you use the variable xs without initializing it! The code:

char xs[len + 2];

declares a character array but does not assign anything to it. So, you have a character array with arbitrary (= 'random') content.

To solve your problem, just initialize xs to an empty string, either when you declare it (see note below), or (better, IMHO) with code like the following before the start of the for loop:

strcpy(xs, "");

Note: You cannot use normal initializer syntax on variable length arrays! So, code like this will not work:

char xs[len + 2] = ""; // Cannot initialize VLA

but you could do this:

char xs[len + 2]; xs[0] = 0;
Adrian Mole
  • 49,934
  • 160
  • 51
  • 83
  • @Syed.bcc: A more obvious `xs[i] = o;` instead of creating then concatenating a temporary string should have circumvented your problem as well. Then you don't have to initialize the string to an empty one first. – Jongware Jan 26 '20 at 13:34
  • @AdrianMole: OP named the variable that picks up the character code `o` ("oh"). There is no need for a `0` (zero) inside the loop. – Jongware Jan 26 '20 at 13:48
  • @usr2564301 OK! I misunderstood - now I get your idea (keeps things simple). – Adrian Mole Jan 26 '20 at 13:56
  • @Syed.bcc See edit (and the linked Q/A) on why you cannot use initializer syntax on your VLA. – Adrian Mole Jan 26 '20 at 14:02
  • @AdrianMole it seems like i should be using memset instead direct assignment. – lag Jan 26 '20 at 14:14
  • @AdrianMole just noticed the edit. thanks for making it clear. – lag Jan 26 '20 at 14:17
  • @Syed.bcc: do not downvote random questions or answers "in revenge". If I considered my approach superior to AdrianMole's (working) answer I would have posted it as such. – Jongware Jan 26 '20 at 15:37