& ldquo; Segmentation fault & rdquo; vs & ldquo; run time & rdquo; Error?

advertisements

Consider this piece of snippet :

  char *str = "hellow Ghost";
  str[0] = 'z';
  printf("%s", str);

It is a segmentation fault. Also does it come under run time memory error ?

What I understood by segmentation fault is : Segmentation fault when you are accessing a memory that doesn't belong to you. It is basically a utility created for you to ease your work without letting you corrupt the memory.

How much and what kind of memory errors Segmentation fault covers and what invokes it to check out that a pointer or reference is wrong dealing with memory.

Run time error also occurs due to improper logic. Apart from that, are there any differences between run time error and segmentation fault regarding memory.


It is a segmentation fault. Also does it come under run time memory error ?

Strictly speaking, its an undefined behavior. You may or may not get segmentation fault. Any thing could happen.

Declaring

char *str = "hellow Ghost";

is equivalent to

char const *str = "hellow Ghost";

String literals are stored in read-only section and any attempt to modify it invokes UB.

C11: J.2 Undefined behavior:

The behavior is undefined in the following circumstances:
...
— The program attempts to modify a string literal (6.4.5).