3

It is undefined behavior to do this?

char *a = "hello";
char b[] = "abcd";
a = b;

My compiler throws no warning, with the maximum warning level.

1 Answer 1

10

There is no UB here. You are simply re-assigning a pointer to point at the address of the start of the array instead.

Note that you are not actually modifying the value that a is pointing at, only a itself, and a is a normal char *.

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

2 Comments

What happen with "hello" is lost?
@cheroky, If you had allocated that memory, it would be a memory leak because you could never free it. However, since it is a string literal whose memory was allocated by the compiler (likely in a read-only region), you could never free it anyways, so not having a pointer to it is irrelevant.

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.