c++ - This code seems to append characters outside allocated range -


i'm playing basic stuff of cpp. i'm new in language... i'm warning question maybe not correctly formulated. appreciate help.

the thing after saw example in www.cplusplus.com/reference/cstdlib/malloc/ found self code:

#include <stdio.h>  int main (void) {   char *str;   str = (char*) malloc(2);   str[0] ='8';   str[1] ='8';   str[2] ='6';   str[3] ='\0';   printf ("%s\n",str); } 

and compiling with:

gcc -o0 -pedantic -wall test2.cpp 

(gcc version 4.7.2)

i no errors , output 886. why no errors? have not passed boundary of allocated space?

i didn't no errors , got output 886. why no errors? have not passed boundary of allocated space?

in case code ok... why example in reference? in other (more probable) case... risks?

thanks!

you don't errors because c , c++ don't bounds checking. overwrote sections of memory weren't using, got lucky , wasn't important. compare putting row of nails wall know there's stud. if miss stud, of time, put hole in plaster, it's dangerous keep doing because eventually, you're going hit 1 of live wires instead.


Comments

Popular posts from this blog

get url and add instance to a model with prefilled foreign key :django admin -

android - Keyboard hides my half of edit-text and button below it even in scroll view -

css - Make div keyboard-scrollable in jQuery Mobile? -