Reputation: 1
How did the array get created, even if malloc
is not used?
#include <stdio.h>
#include <stdlib.h>
int main() {
int n,i,*ptr,sum=0;
printf("Enter number of elements: ");
scanf("%d",&n);
printf("Enter elements of array: ");
for(i=0;i<n;++i)
{
scanf("%d",ptr+i);
sum+=*(ptr+i);
}
printf("Sum=%d",sum);
free(ptr);
return 0;
}
Upvotes: 0
Views: 184
Reputation: 4801
The array is not "created". It is declared. Then it is not defined or initialized. You use it.
Undefined behavior.
If you used a more stricter compiler, then you would have gotten:
warning: ‘ptr’ may be used uninitialized in this function [-Wmaybe-uninitialized]
Therefore it is actually not dynamic.
The bigger question here in my opinion is what happens with free(ptr)
:
It is possible, but is also undefined behavior. Since you pass an uninitialized pointer, the value of the pointer is not clear. It might be by accident NULL
but not limited to.
The big picture:
Accessing any uninitialised variable results in undefined behavior.
EDIT:
OP didn't declare an array, rather an integer pointer.
Upvotes: 2