c++ - Merge 2 sorted arrays in C -


i'm writing code merge 2 sorted arrays code 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 code program stops , 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 fix it

the problem did not provide space in merged information should placed. provided uninitialized pointer c sorted parameter, gets dereferenced inside function, causing undefined behavior.

to fix this, pass array sufficient capacity hold elements of merged array:

int a[]={7, 15, 20}; int b[] = {8, 12, 19, 32}; int c[7]; merge(a, b, c, 3, 4); 

Comments

Popular posts from this blog

Magento/PHP - Get phones on all members in a customer group -

php - Bypass Geo Redirect for specific directories -

php - .htaccess mod_rewrite for dynamic url which has domain names -