I was writing a simple compiler just for fun and I wanted each line to have proper indentation.
So I wrote a function that returns an array of characters with some white-spaces depending on the number.
The problem is that when the array is generated some characters seem to be wrong at the time of writing the in the file or just printing. I think they are taken from a memory location with some information because I saw a fragment of a file path.
I made an example code that has the same problem
int num = 0;
char *tabs;
for (; num < 20; num++)
{
tabs = malloc(num);
memset(tabs, '-', num);
printf("%d | %sEND\n", num, tabs);
}
(I suppose it's not the best code but I'm a beginner in C)
Output:
0 | Çc▬END
1 | -s▬END
2 | --▬END
3 | ---END
4 | ----END
5 | -----END
6 | ------END
7 | -------END
8 | --------P☺▬END
9 | ---------☺▬END
10 | ----------▬END
11 | -----------END
12 | ------------END
13 | -------------END
14 | --------------END
15 | ---------------END
16 | ----------------END
17 | -----------------END
18 | ------------------END
19 | -------------------END
The characters are different everytime I run the program.
If instead of memset I use a for loop to set each character the result will be the same.
I read that memset would solve the problem but I didn't.