I read about dynamic memory allocation in C using this link.
This document will say:
realloc () should only be used for dynamically allocated memory. If the memory is not allocated dynamically, then the behavior is undefined.
If we use realloc()
something like this:
int main()
{
int *ptr;
int *ptr_new = (int *)realloc(ptr, sizeof(int));
return 0;
}
According to this link, this program is undefined because the ptr pointer is not allocated dynamically.
But, if I use something like:
int main()
{
int *ptr = NULL;
int *ptr_new = (int *)realloc(ptr, sizeof(int));
return 0;
}
Is this also undefined behavior according to this link?
In this case, the second case does not cause undefined behavior. I'm right?
source
share