This has no runtime error
int main()
{
char *p = "Hello";
}
This gives runtime error
int main()
{
int *p;
*p = 5;
}
I cant understand the reason why this is happening. Would appreciate any kind of help.
Your first example points pointer p to a literal string, so p is pointing to valid memory.
Your section declares the pointer p but does not point to to any memory address. Then the next statement *p = 5 dereferences p, which tries to store 5 at the memory address stored in pointer p. Since you have not pointed p to valid memory, your application crashes.
Your second snippet is undefined behaviour as the pointer is uninitialised.
Your first snippet could get you into trouble too: you ought to write const char *p = "Hello";. This is because the string text will be added to a table of string literals by the C runtime library. It's undefined behaviour to modify it. Using const helps enforce that.
The first program sets the value of the pointer, and is well-defined (so long as you don't attempt to modify the string).
The second program assigns a value through an uninitialized pointer (and therefore has undefined behaviour).
The following is a rough equivalent of the first program, but using int:
int main()
{
int val = 5;
int *p = &val;
}
pin the first snippet asconst char*instead ofchar*. This will make the compiler catch any assignments to*p, which would result in undefined behavior, which is invoked by writing to string literals.