Reputation: 331
I'm writing code to merge 2 sorted arrays code is below
void main()
{
int a[]={7};
int b[] = {8};
int ret;
int *c;
merge(a,b,c,1,1);
}
void merge(int *a, int *b,int *sorted, int i, int j)
{
int c1,c2,k=0;
c1=0;
c2=0;
for(k=0;c1<i && c2< j;k++)
{
if(a[c1]<b[c2])
sorted[k]=a[c1++];
else
sorted[k]=b[c2++];
}
while(c1<i)
sorted[k++]=a[c1++];
while(c2<j)
sorted[k++]=b[j++];
}
When running this code program stops and I get the below exception
Problem Event Name: APPCRASH
Application Name: merge.exe
Application Version: 0.0.0.0
Application Timestamp: 556fb91c
Fault Module Name: merge.exe
Fault Module Version: 0.0.0.0
Fault Module Timestamp: 556fb91c
Exception Code: c0000005
Exception Offset: 00001739
OS Version: 6.1.7601.2.1.0.768.3
Locale ID: 2057
Additional Information 1: 0a9e
Additional Information 2: 0a9e372d3b4ad19135b953a78882e789
Additional Information 3: 0a9e
Additional Information 4: 0a9e372d3b4ad19135b953a78882e789
How to fix it
Upvotes: 0
Views: 950
Reputation: 726489
The problem is that you did not provide any space in which the merged information should be placed. You provided an uninitialized pointer c
for the sorted
parameter, which gets dereferenced inside the function, causing undefined behavior.
To fix this, pass an array with sufficient capacity to hold elements of the merged array:
int a[]={7, 15, 20};
int b[] = {8, 12, 19, 32};
int c[7];
merge(a, b, c, 3, 4);
Upvotes: 7