Yesterday i learnt few strange things about malloc() in C and new, delete operators in C++.
Compiler referred is gcc for C, and g++ for C++ programs.First one:
int *a=malloc(sizeof(int) *0); //i am trying to allocate 0 bytes of memory and pointing that location with pointer a.
==> What should happen, Segmentation fault( run time error) , since allocating 0 bytes of memory is absurd and then referencing it through a pointer a is too wrong. It went through compilation and run perfectly on 'dereferencing' as a[0]=5, a[1]=2,... .
==> But i get segfault when i am trying to allocate -ve bytes of memory.
Second one:
int *a= new int[0];==> the same effect with 0 size memory allocation and runtime error when trying to allocate (-ve)size of memory.
Third one:
This one, i strongly beleive that it sould raise runtime error, as it is mentioned in C++ standards.
int* a=new int[10];......delete a; //Here it should be delete[] a;
==> When an array of objects are created with new operator, while deleting all objects, we should use delete[], instead of delete; since delete will only delete that object.
Fourth one:
Do you think that on freeing or deleting the dynamic memory, the contents/memory locations will be deleted permanantly? No, it shouldn't be. The compiler will just cut of those associated links and the memory locations still with the content that we have assigned. If u want to try, assign the locations to other pointer before freeing/deleting.
My experience is:
int *a=malloc(sizeof(int)*4);a[0]=1;a[1]=2;a[2]=3;a[3]=4;int *t;t=a;free(a); printf("%d , %d , %d , %d ",t[0],t[1],t[2],t[3]);//Answer is "0 , 2 , 3 , 4"
int *a=new int[4];
a[0]=1;a[1]=2;a[2]=3;a[3]=4;
int *t;
t=a;
delete(a);
printf("%d , %d , %d , %d ",t[0],t[1],t[2],t[3]);//Answer is "0 , 2 , 3 , 4"
==> I am not able to figure out the logic behind making the value of base address to 0 upon deleting. If it is to make value of deleted location as '0', then it should be with all the locations that are dynamically created. But it isn't. And also one more thing is 'write' operation is more costly than delinking.
Your comments are appreciated, if you have proper reasons.