Abort instead of segfault with clear memory violation

后端 未结 6 588
渐次进展
渐次进展 2021-01-13 18:48

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

6条回答
  •  旧巷少年郎
    2021-01-13 19:23

    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.

提交回复
热议问题