0

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.

2
  • I stared at this for a minute and couldn't see the problem. Not worth a question downvote in my opinion. Update: glad to see it's removed. Commented Oct 26, 2013 at 20:10
  • In addition to the provided answers, you should (in this case) declare p in the first snippet as const char* instead of char*. This will make the compiler catch any assignments to *p, which would result in undefined behavior, which is invoked by writing to string literals. Commented Oct 26, 2013 at 20:11

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

1

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;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.