Abort instead of segfault with clear memory violation
c, memory-management
Solution
I thought that when strcat tries to write to `s1` at indexes higher than `6` the program would segfault.
Writing outside the bounds of memory you have allocated on the stack is undefined behaviour. Invoking this undefined behaviour usually (but not always) results in a segfault. However, you can't be sure that a segfault will happen.
The wikipedia link explains it quite nicely:
When an instance of undefined behavior occurs, so far as the language specification is concerned anything could happen, maybe nothing at all.
So, in this case, you could get a segfault, the program could abort, or sometimes it could just run fine. Or, anything. There is no way of guaranteeing the result.
Where are these strings in memory (the stack, or the heap)?
Since you've declared them as `char []` inside `main()`, they are arrays that have automatic storage, which for practical purposes means they're on the stack.
Problem
I came upon this weird behaviour when dealing with C strings. This is an exercise from the K&R book where I was supposed to write a function that appends one string onto the end of another string. This obviously requires the destination string to have enough memory allocated so that the source string fits. Here is the code: ``` /* strcat: Copies contents of source at the end of dest */ char *strcat(char *dest, const char* source) { char *d = dest; // Move to the end of dest while (*dest != '\0') { dest++; } // *dest is now '\0' while (*source != '\0') { *dest++ = *source++; } *dest = '\0'; return d; } ``` During testing I wrote the following, expecting a segfault to happen while the program is running: ``` int main() { char s1[] = "hello"; char s2[] = "eheheheheheh"; printf("%s\n", strcat(s1, s2)); } ``` As far as I understand s1 gets an array of 6 `chars` allocated and s2 an array of 13 `chars`. I thought that when `strcat` tries to write to s1 at indexes higher than 6 the program would segfault. Instead everything works fine, but the program doesn't exit cleanly, instead it does: ``` helloeheheheheheh zsh: abort ./a.out ``` and exits with code 134, which I think just means abort. Why am I not getting a segfault (or overwriting s2 if the strings are allocated on the stack)? Where are these strings in memory (the stack, or the heap)? Thanks for your help.