/* "Array out of bounds" errorvalid indices for array fooare 0, 1, ... 999 */int foo[1000];for (int i = 0; i <= 1000 ; i++)foo[i] = i;
这里i[1000]不存在,所以发生了分段错误。
分割错误原因:
it arise primarily due to errors in use of pointers for virtual memory addressing, particularly illegal access.
De-referencing NULL pointers – this is special-cased by memory management hardware.
Attempting to access a nonexistent memory address (outside process’s address space).
Attempting to access memory the program does not have rights to (such as kernel structures in process context).
Attempting to write read-only memory (such as code segment).
int num;scanf("%d", num);// must use &num instead of num
以错误的方式使用指针。
int *num;printf("%d",*num); //*num should be correct as num only//Unless You can use *num but you have to point this pointer to valid memory address before accessing it.
修改字符串文字(指针尝试写入或修改只读内存。)
char *str;
//Stored in read only part of data segmentstr = "GfG";
//Problem: trying to modify read only memory*(str+1) = 'n';
尝试通过已经释放的地址到达。
// allocating memory to numint* num = malloc(8);*num = 100;
// de-allocated the space allocated to numfree(num);
// num is already freed there for it cause segmentation fault*num = 110;