thephysicsguy thephysicsguy - 1 month ago 6x
C Question

Why is there random characters in my char array?

When I compile and run the following in C,

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main ()
char func[16];
for(int i = 0; i < sizeof(func); i++) {
printf("Char %d in func is %c\n", i, func[i]);
return 0;

I get this:

Char 0 in func is P
Char 1 in func is
Char 2 in func is @
Char 3 in func is
Char 4 in func is
Char 5 in func is
Char 6 in func is
Char 7 in func is
Char 8 in func is p
Char 9 in func is
Char 10 in func is @
Char 11 in func is
Char 12 in func is
Char 13 in func is
Char 14 in func is
Char 15 in func is

and when I compile at different times I get different random characters in my char array. I am guessing this is because it finds random ASCII characters in the memory of which the pointers were deleted but the actual information was left in the heap?

Should I bother setting everything to null in my array in a for loop or is there a function which does it?


Uninitialized local non-static variables, like your array func, haven an indeterminate value. Using them in any way without initialization leds to undefined behavior.

In reality the contents will be whatever happens to be in memory at the moment you run your program. It will be seemingly random.