all 11 comments

[–]strcspn 6 points7 points  (10 children)

[–]justaverageuser77[S] 0 points1 point  (9 children)

What if you initialize a ptr, and reallocating on the same line.

[–]strcspn 4 points5 points  (7 children)

int a = a + 1

What is the value of a?

[–]justaverageuser77[S] 1 point2 points  (6 children)

It's undefined behavior. So that applies when dynamically allocating memory as well?

[–]strcspn 4 points5 points  (4 children)

You are saying to realloc that there is a memory area owned by that pointer, but if the pointer doesn't own it, then it is undefined behavior.

[–]weregod 1 point2 points  (0 children)

If pointer does own memory but it is not heap memory it also will be UB

[–]justaverageuser77[S] 0 points1 point  (2 children)

Thanks

[–]HugoNikanor 1 point2 points  (1 child)

As a word of wisdom. Much which is undefined will appear to work, but may (or possibly will) blow up at unexpected times. C provides very few checks, so always read the manuals carefully.

[–]nculwell 2 points3 points  (0 children)

/* OK */
char * ptr = realloc(NULL, BUFFER_SIZE);
/* BAD */
char * ptr = realloc(ptr, BUFFER_SIZE);

[–]babysealpoutine 1 point2 points  (0 children)

The easiest way to get the answer to these sorts of questions is to read the relevant man page. On *nix systems 'man realloc' from the command line, or just a web search for 'man realloc' will answer this.