c - Abort instead of segfault with clear memory violation -


i came upon weird behaviour when dealing c strings. exercise k&r book supposed write function appends 1 string onto end of string. requires destination string have enough memory allocated source string fits. here code:

 /* strcat: copies contents of source @ end of dest */  char *strcat(char *dest, const char* source) {   char *d = dest;   // move end of dest   while (*dest != '\0') {     dest++;   } // *dest '\0'    while (*source != '\0') {     *dest++ = *source++;   }   *dest = '\0';   return d; } 

during testing wrote following, expecting segfault happen while program running:

int main() {   char s1[] = "hello";   char s2[] = "eheheheheheh";    printf("%s\n", strcat(s1, s2)); } 

as far understand s1 gets array of 6 chars allocated , s2 array of 13 chars. thought when strcat tries write s1 @ indexes higher 6 program segfault. instead works fine, program doesn't exit cleanly, instead does:

helloeheheheheheh zsh: abort      ./a.out 

and exits code 134, think means abort.

why not getting segfault (or overwriting s2 if strings allocated on stack)? these strings in memory (the stack, or heap)?

thanks help.

i thought when strcat tries write s1 @ indexes higher 6 program segfault.

writing outside bounds of memory have allocated on stack undefined behaviour. invoking undefined behaviour (but not always) results in segfault. however, can't sure segfault happen.

the wikipedia link explains quite nicely:

when instance of undefined behavior occurs, far language specification concerned happen, maybe nothing @ all.

so, in case, segfault, program abort, or run fine. or, anything. there no way of guaranteeing result.

where these strings in memory (the stack, or heap)?

since you've declared them char [] inside main(), arrays have automatic storage, practical purposes means they're on stack.


Comments

Popular posts from this blog

basic authentication with http post params android -

vb.net - Virtual Keyboard commands -

How to get multiresult with multicondition in Sql Server -