Abort instead of segfault with clear memory violation

后端 未结 6 547
渐次进展
渐次进展 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:16

    hmm.... the strings are in stack all right since heap is used only for dynamic allocation of memory and stuff..

    segfault is for invalid memory access, but with this array you are just writing stuff which is going out of bound (outside the boundry) for the array , so while writing i dont think you will have a issue .... Since in C its actually left to the programer to ensure things are kept in bound for arrays.

    Also while reading if you use pointers - I dont think there will be a issue either since you can just continue to read till where ever you want and using the sum of previous lengths. But if you use functions that are mentioned in string.h they relay on the presence of the null character "\0" to decide where to halt the operation -- hence i think your function worked !!

    but the termination could also indicate that any other variable / something that might have been present next to the location of the strings might have got over written with char value .... accessing those might have caused the program to exit !!

    hope this helps .... good question by the way !

提交回复
热议问题