if we assign a pointer to another pointer, it's called "swap the pointers". For example,
float *temp, *ptr1, *ptr2;
temp = ptr1;
ptr1 = ptr2;
ptr2 = temp;
However, if we assign an array to a pointer, it's illegal because array is not really the pointer type. But look at the next 3 examples:
float arr[]={1.2, 1.9, 3.1};
float *ptr;
int i;
ptr = (float *)calloc(3,sizeof(float));
ptr = arr;
for (i=0;i<3;i++){
printf("ptr[%d]=%f\n",i,ptr[i]);
}
This code snippet passed the compilation and ran correctly (illegal code gets the correct answer?):
ptr[0]=1.200000
ptr[1]=1.900000
ptr[2]=3.100000
If I add free(ptr) following the last line, i.e.
float arr[]={1.2, 1.9, 3.1};
float *ptr;
int i;
ptr = (float *)calloc(3,sizeof(float));
ptr = arr;
for (i=0;i<3;i++){
printf("ptr[%d]=%f\n",i,ptr[i]);
}
free(ptr); /*add free here*/
This time a warning came up:
warning: attempt to free a non-heap object ‘arr’ [-Wfree-nonheap-object]
int i;
int flag=0;
float arr1[3]={1.07,3.01,5.02};
float arr2[3]={2.07,6.01,9.02};
float arr3[3]={3.07,8.01,0.02};
float *ptr;
ptr = (float *)calloc(3,sizeof(float));
if(flag==0){
ptr = arr1;
}
else if(flag==1){
ptr = arr2;
}
else{
ptr = arr3;
}
for (i=0;i<3;i++){
printf("ptr[%d]=%f\n",i,ptr[i]);
}
It can run correctly with different flag, but if I add free(ptr) at last line, it still has warning like the previous.
Does anybody help analyze why?
ptrto hold that memory location. On the next line change the value ofptrto hold the address of thearrarray, orphaning the memory you previously allocated. Since the memoryptrpoints to is actually a literal array of three floats you cannot free it. The memory you should be freeing has been leaked.malloccallocrealloc1) the returned type isvoid*which can be assigned to any pointer. Casting just clutters the code, making it more difficult to understand, debug, etc. 2) always check (!=NULL) the returned value to assure the operation was successfulptr = arr1;and similar statements. This overlays the value set in the pointer via the call tocalloc(), resulting in a memory leak. Perhaps you meant:memcpy( ptr, arr1, sizeof( arr1) );Note: in C, referencing the name of an array degrades to the address of the first byte of the array.