3 ms·
Not a C guy. Why are these functions unsafe?
by benihana 13y ago
Not a C guy. Why are these functions unsafe?
- Roboprog 13y agoHere, runtime, make some results and put them into this (character array) buffer I'm providing for you. Oh, the buffer wasn't big enough? Well, I'm sure the stuff after the buffer's end that you wrote over wasn't all that important, anyway. Probably just a few neighboring local variables that my function was storing nearby on the stack, or maybe the return address on the stack, or maybe the heap management data (block size field, free list pointer, ...) around the block of memory I allocated from the heap. I wonder what the next pass of my loop will do now, or what will happen when this function returns???
- tbrownaw 13y agoBecause C strings are arrays of characters terminated by a null ('\0') character, and arrays in C don't have bounds checking and don't come with a length attached. If you allocate a 10-element character array, it can hold strings of up to 9 characters (plus the null terminator). But, the library functions ("runtime") don't know how big it is. So if you try to copy a 20-character string into that 10-element buffer, it will copy 21 characters. The first 10 will go into the array, and the next 11 characters will go... somewhere else. Depending on where in memory your array and other things are, something important will probably get overwritten with garbage.