0

I recently re-started learning C and well decided to conquer what put me off last time: pointers! So I'm experimenting with strings and pointers to see how things react and finally wrap my brain around the beast.

Now I declared a char string[256] that I am later iterating through using a pointer (code block at the end of the post). I have "declared" but not "initialised" (I'm very proud to know the difference!) the string so I can see what data lies in the memory that the string points to.

When I run the program, the output is obviously gibberish of mixed ascii characters / question marks that, I imagine, indicate binary data. All is well!

BUT

(TLDR; marker:) I notice that I get surprisingly little gibberish so I try to reduce the size of my char array to see when weird stuff starts to appear and there is a very clear threshold at 249 characters. Any value below that returns an empty line.

Why is this? Why 249 characters? Is it just that there is no program using this part of the RAM at the moment or is there a more intricate explanation?

int main(void){
    char string[248];

    for (const char *c = string; *c; c++) {
        printf("%c", *c);
    }
}

Mr Fry
  • 11
  • 2
  • 3
    The array `string` is not initialized, as you correctly say. That means its contents will be *indeterminate*. There's no guarantee that there will be any valid characters, or even a string null-terminator, in the array. Which means you can go *way* out of bounds of the array with your loop, and end up with *undefined behavior*. And C doesn't have any kind of bound-checking. – Some programmer dude Mar 25 '23 at 20:44
  • An empty line could be one of two things: 1) the first byte was a 0, so the `printf` never gets called, or 2) the values in the array don't have visible representations, e.g. spaces and tabs. Change the code to `for (const char *c = string; c - string < 248; c++) printf("%02x\n", (unsigned char)(*c));` to see what's actually in the array. – user3386109 Mar 25 '23 at 20:54
  • Oh cool! Now I can see that the value is always the same length: 6 bytes, which is the last 6 bytes of the 256 bytes array indeed. I understand the use of the format specifier %02n and the unsigned char but not the parentheses. It looks like a function pointer or something... – Mr Fry Mar 25 '23 at 22:00
  • The second parentheses are not needed: you could write `(unsigned char)*c`. It dereferences the pointer `c` and casts the result to `unsigned char`. Nothing to do with function pointers. – Nate Eldredge Mar 25 '23 at 22:05

0 Answers0