c++ - Why would this code give a segfault only for some cases? -


i trying code word-ram version of subset sum. (it basic dp algorithm, , algo should not important determine problem code). minimum code needed reproduce error think:

#include <stdio.h> #include <stdlib.h> #include <math.h>   // bit #bitno num. 0 significant. unsigned int getbit(unsigned int num, int bitno){      unsigned int w = sizeof(int)*8;  //for regular word.     int shiftno = w-bitno-1;     unsigned int mask = 1<<shiftno;     unsigned int maskedn = num&mask;     unsigned int thebit = maskedn>>shiftno;     return thebit; }  /* no boundary array right shift */ unsigned int* nbars(unsigned int orig[], unsigned int x){      int alength = sizeof(orig)/sizeof(orig[0]);     unsigned int b_s = sizeof(int)*8;     unsigned int * shifted;     shifted = new unsigned int[alength];     int i;     for(i=0;i<alength;i++){         shifted[i] = 0;     }      unsigned int aux1 = 0;     unsigned int aux2 = 0;      int bts = floor(x/b_s);     int split = x%b_s;     = bts;     int j = 0;     while(i<alength){         aux1 = orig[j]>>split;         shifted[i] = aux1|aux2;         aux2 = orig[j]<<(b_s-split);         i++;j++;     }      return shifted; }  /* returns true if there subset of set[] sum equal t */ bool issubsetsum(int set[],int n, int t){     unsigned int w = sizeof(int)*8;  //for regular word.     unsigned int wordsneeded = ceil(double(t+1)/w);     unsigned int elements = n;     //create table     unsigned int table[elements][wordsneeded];     int c,i;     //initialize first row     for(i=0;i<wordsneeded;i++){         table[0][i] = 0;     }     table[0][0] = 1<<(w-1);     //fill table in bottom manner     int es,ss,ai;     for(c=1;c<=elements; c++){          unsigned int *aux = nbars(table[c-1],set[c-1]);         for(i=0;i<wordsneeded;i++){             table[c][i] = table[c-1][i]|aux[i];         }         }      if((table[elements][wordsneeded-1]>>((w*wordsneeded)-t-1))&1 ==1){           return true;      }return false; }   int main(){       int set[] = {81,80,43,40,30,26,12,11,9};     //int sum = 63;     int sum = 1000;      int n = sizeof(set)/sizeof(set[0]);     if (issubsetsum(set,n,sum) == true)      printf("\nfound subset given sum\n");   else      printf("\nno subset given sum\n");   return 0; } 

ok. if run example target sum of 63, works fine. gives right answer , true, , if run code print subset prints right subset. however, if change sum larger one, 1000 in code, following error:

program received signal sigsegv, segmentation fault. 0x0000000000400af1 in issubsetsum (set=0x0, n=0, t=0) @ redss.cpp:63 63          unsigned int *aux = nbars(table[c-1],set[c-1]); 

from gdb. don't understand why fail larger sums, since process should same... missing obvious? great!!!


Comments