Is the free(ptr2) going to delete my array as I want ?
I think the term delete
cannot be used here. The GNU manual says :
When you no longer need a block that you got with malloc, use the
function free to make the block available to be allocated again.
However free doesn't set pointer automatically to NULL because the function return type itself is void
. Also,
Freeing a block alters the contents of the block. Do not expect to
find any data (such as a pointer to the next block in a chain of
blocks) in the block after freeing it.
I am not spurring a debate on whether you should set the pointer to NULL after freeing it. However,I felt tempted to post this example which crashes and burns :
#include<stdio.h>
#include<stdlib.h>
int main()
{
int* ptr1 = malloc(sizeof(int)*10);
int* ptr2 = ptr1;
free(ptr2);
if(ptr2!=NULL)
{
printf("ptr is %p\n",ptr2); // still printf
printf("Enter a number for ptr2 :");
scanf("%d",ptr2);
printf("Value pointed to by ptr2 : %d\n",*ptr2);
printf("Value pointed to by ptr1 : %d\n",*ptr1);
}
else
printf("Ptr2 pointed to null");
printf("Size of ptr1 : %d\n",sizeof(ptr1));
if(ptr1==NULL)
printf("ptr1 NULL\n");
printf("Enter a number for ptr1 :");
scanf("%d",ptr1);
printf("Value pointed to by ptr1 : %d\n",*ptr1);
printf("Value pointed to by ptr2 : %d\n",*ptr2);
free(ptr1);
if(ptr1==NULL)
printf("ptr1 freed\n");
return 0;
}
Output
ptr is 0x1c92010
Enter a number for ptr2 :4
Value pointed to by ptr2 : 4
Value pointed to by ptr1 : 4
Size of ptr1 : 8
Enter a number for ptr1 :1
Value pointed to by ptr1 : 1
Value pointed to by ptr2 : 1
*** glibc detected *** ./testp: double free or corruption (fasttop): 0x0000000001c92010 ***
Segmentation fault (core dumped)