Home > OS >  segmentation fault in 2d array
segmentation fault in 2d array

Time:05-26

I am writing the code about the lcs algorithm. Because of the condition, I made the 2d lcs_table for the lcs algorithm by using malloc function. While the initializing the array as 0, there is segmentation fault. I don't know where is wrong..

void findLCS(char lcs_1[], const char s1[], const char s2[])
{
  /* FILL */
  int i,j,k,l;
  int s1_len = strlen(s1);
  int s2_len = strlen(s2);
  // int LCS_array[s1_len 1][s2_len 1];  //>>malloc use
  //printf("%d, %d\n",s1_len, s2_len);
  int **LCS_array;
  LCS_array = malloc(sizeof(char)*(s1_len 1));
  for(i=0;i<=s1_len;i  ){
    LCS_array[i] = malloc(sizeof(char)*(s2_len 1));
    if(LCS_array[i]==NULL){
      perror("malloc:");
      exit(1);
    }
  }
  printf("s1_len : %d, s2_len : %d\n",s1_len,s2_len);
  for (i = 0 ; i <=s1_len;i  ){
    for (j = 0 ; j <=s2_len;j  ){
        printf("[%d,%d] ",i,j);
        LCS_array[i][j] = 0;
    }
    printf("\n");
  }

  for(i = 1 ;i<=s1_len;i  ){
      for(j = 1;j<=s2_len;j  ){
          if (s1[i-1]==s2[j-1]){
            LCS_array[i][j] =(LCS_array[i-1][j-1] 1);
          }
          else if(LCS_array[i-1][j]>=LCS_array[i][j-1]){
            LCS_array[i][j] =LCS_array[i-1][j];
          }
          else{
            LCS_array[i][j]=LCS_array[i][j-1];
          }
      }
  }

  int index = LCS_array[s1_len][s2_len];
  lcs_1[index] = '\0';

  i = s1_len, j = s2_len;
  while (i > 0 && j > 0) {
    if (s1[i - 1] == s2[j - 1]) {
      lcs_1 [index-1] = s1[i-1];
      i--;
      j--;
      index--;
    }
    else if (LCS_array[i - 1][j] < LCS_array[i][j - 1])
      j--;
    else
      i--;
  } 
}
jeon@ubuntu:~/hw5$ ./hw5_cor ccgtttcca tgcccatct
$ ./hw5_cor ccgtttcca tgcccatct 
s1_len : 9, s2_len : 9
[0,0] [0,1] [0,2] [0,3] [0,4] [0,5] [0,6] [0,7] [0,8] [0,9] 
[1,0] [1,1] [1,2] [1,3] [1,4] [1,5] [1,6] [1,7] [1,8] [1,9] 
[2,0] [2,1] [2,2] [2,3] [2,4] [2,5] [2,6] [2,7] [2,8] [2,9] 
[3,0] [3,1] [3,2] [3,3] [3,4] [3,5] [3,6] [3,7] [3,8] [3,9] 
Segmentation fault (core dumped)

Where do I correct the code?

CodePudding user response:

The LCS_array = malloc(sizeof(char)*(s1_len 1)); should be LCS_array = malloc(sizeof(char*)*(s1_len 1)); with an additional asterisk after char keyword. This is because LCS_array is a pointer of pointers, in other words it should be an array in which each element is also a pointer to an integer array.

Refer to this article from Geeksforgeeks for more info about creating 2D array in C. I think this should solve the segmentation fault problem (I'm not sure because I'm on windows).

Here's an example on how to create a 2D array dynamically in C from the GFG article:

    int r = 3, c = 4, i, j;
 
    int** arr = (int**)malloc(r * sizeof(int*));
    for (i = 0; i < r; i  )
        arr[i] = (int*)malloc(c * sizeof(int));
  • Related