c - longest common subsequence: why is this wrong? -


int lcs(char * a, char * b) {   int m = strlen(a);   int n = strlen(b);   int *x = malloc(m * sizeof(int));   int *y = malloc(n * sizeof(int));   int i;   int j;   (i = m; >= 0; i--)     {       (j = n; j >= 0; j--)         {           if (a[i] == '\0' || b[j] == '\0')                x[j] = 0;           else if (a[i] == b[j])                x[j] = 1 + y[j+1];           else                x[j] = max(y[j], x[j+1]);         }       y = x;     }   return x[0]; } 

this works, valgrind complains loudly invalid reads. how messing memory? sorry, fail @ c memory allocation.

the issue here size of table. note you're allocating space as

int *x = malloc(m * sizeof(int)); int *y = malloc(n * sizeof(int)); 

however, using indices 0 ... m , 0 ... n, means there m + 1 slots necessary in x , n + 1 slots necessary in y.

try changing read

int *x = malloc((m + 1) * sizeof(int)); int *y = malloc((n + 1) * sizeof(int)); 

hope helps!


Comments

Popular posts from this blog

SPSS keyboard combination alters encoding -

Add new record to the table by click on the button in Microsoft Access -

CSS3 Transition to highlight new elements created in JQuery -