F
F
forgoty2018-05-19 23:50:10
C++ / C#
forgoty, 2018-05-19 23:50:10

Why does gcc printf(%s, array) correctly output a char array that is not a NULL-terminated string?

#include <stdio.h>

int main() {
    char foo[6] = {"123456"};
    printf("%s", foo); // 123456
}

Why is gcc outputting the given array correctly? After all, the specifier %s means to display all the characters in the array until it encounters \0. But it is clearly not set. I expected to see just a stream of random bytes from memory until I encountered \0 somewhere.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
rhaport, 2018-05-20
@forgoty

Lucky. The next address after the array contains zero. The array is created on the stack. Your simple program doesn't litter the stack. It is likely that the next element is simply 0. Look in the debugger for the value of foo[6] or print

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question