Reputation: 65
I wrote a merge sort. When I changed the 35 lines of code to malloc(NULL), I found that the program could still sort the results without reporting an error. Why is this happening?
There is a warning at malloc(NULL) but no error.
int sort(int*a,int n){
int *p=(int *)malloc(NULL);
g_sort(a,0,n-1,p);
return 1;
}
The code can be run to sort the correct result:
#include<bits/stdc++.h>
using namespace std;
void m_qsort(int *a,int left,int mid,int right,int*temp){
int m=mid;int r=right;
int k=0,j=mid+1;;
int l=left;
while(l<=m && j<=r){
if(a[l]<=a[j])
temp[k++]=a[l++];
else
temp[k++]=a[j++];
}
while(l<=mid){
temp[k++]=a[l++];
}
while(j<=r){
temp[k++]=a[j++];
}
for(int i=0;i<k;i++){
a[left+i]=temp[i];
}
}
void g_sort(int *a,int left,int right,int*temp){
if(left<right){
int mid=(left+right)>>1;
g_sort(a,left,mid,temp);
g_sort(a,mid+1,right,temp);
m_qsort(a,left,mid,right,temp);
}
}
int sort(int*a,int n){
int *p=(int *)malloc(NULL);
g_sort(a,0,n-1,p);
return 1;
}
int main()
{
int a[22]={8,4,7,5,6,2,1,7,10,25,0,1,75,52,14,56,33,24,852,20,26,41};
sort(a,22);
for(int i=0;i<22;i++){
cout<<a[i]<<' '<<endl;
}
}
Result:
$g++ -o main *.cpp
main.cpp: In function ‘int sort(int*, int)’:
main.cpp:46:27: warning: passing NULL to non-pointer argument 1 of ‘void* malloc(size_t)’ [-Wconversion-null]
int *p=(int *)malloc(NULL);
^
$main
0
1
1
2
4
5
6
7
7
8
10
14
20
24
25
26
33
41
52
56
75
852
Upvotes: 0
Views: 75
Reputation: 96
According to this documentation, requesting a 0 size as you did is implementation-defined. Your system's implementation probably returns a non-null pointer, because a null pointer would segfault on most systems (see Scheff's Cat's comment below for why I say "most"). The documentation says not to use this pointer, so you're violating malloc
's contract. I take it that your question is for your curiosity.
Maybe it's returning an address within the heap, and your program is buffer-overrunning into adjacent virtual memory addresses that were allocated to your process. You may be able to use heap analysis tools to confirm this. This StackOverflow question has answers with some heap analysis tools.
Upvotes: 3