2015-01-31 1 views
1

프로그램이 한 줄에 여러 단어로 된 txt 파일을 받아 들여서 편집 거리를 찾는 ac/C++ 프로그램을 만들려고합니다 (levenshtein 거리)를 특정 단어와 비교합니다.프로그램을 실행할 때 런타임 오류가 발생하지만 디버거를 사용하지 않는 경우

이상한 문제가 있습니다.

코드 블록에서 실행할 때 내 코드에서 몇 단어를 읽은 후 런타임 오류가 발생합니다. 그것은 코드 블록 디버거를 사용할 때 잘 디버그됩니다.

나는 주변을 둘러 보았고 초기화되지 않은 변수가 문제가 될 수 있음을 발견했습니다. 하지만 언제든지 내가 함수를 호출하는 라인을 주석 minDistancecount[i]=minDistance(word,lines[i]);, 코드가 잘 실행되고 파일의 모든 단어를 출력합니다. 그래서 그건 내가 추측하는 문제가 아니다.

도움이 될 것입니다. 고맙습니다.

다음은 코드입니다.

#include <stdio.h> 
#include <string.h> 
#include <stdlib.h> 
#include<iostream> 


using namespace std; 
static int minDistance(char* word1, char* word2) 
{ 
    const int l1 = strlen(word1); 
    const int l2 = strlen(word2); 
    int i=0,j=0; 
    int **d = new int*[l2 + 1]; 
    for(i=0;i<l1+1;++i) 
     d[i]=new int[l1+1]; 

    // the edit distance between an empty string and the prefixes of 
    // word2 
    for (i = 0; i < l2 + 1; i++) { 
     d[0][i] = i; 
    } 

    // the edit distance between an empty string and the prefixes of 
    // word1 
    for (j = 0; j < l1 + 1; j++) { 
     d[j][0] = j; 
    } 

    for (i = 1; i < l1 + 1; i++) { 
     for (j = 1; j < l2 + 1; j++) { 
      if (word1[i - 1] == word2[j - 1]) { 
       d[i][j] = d[i - 1][j - 1]; 
      } else { 
       d[i][j] = min(min(1 + d[i][j - 1], 1 + d[i - 1][j]), 
       1 + d[i - 1][j - 1]); // min of insertion, 
       // deletion, replacement 
      } 
     } 
    } 

    return d[l1][l2]; 
} 

void lines() 
{ 
    int i=0; 
    char * lines[10]; 
    int count[10]; 
    char word[]="book"; 
    FILE *file_handle = fopen ("wordlist.txt", "r"); 

    for (i =0; i < 5; ++i) 
    { 
    lines[i] = (char*)malloc (128); /* allocating a memory slot of 128 chars */ 
    fscanf (file_handle, "%s", lines[i]); 
    count[i]=minDistance(word,lines[i]); 
    cout<<lines[i]<<" "; 
    cout<<count[i]<<endl; 
    } 

    for (i =0; i < 5; ++i) 
    free (lines[i]); 

} 
int main (int argc, char *argv[]) 
{ 
    lines(); 
    return 0; 
} 
+0

# 1. std :: string ans std :: vector를 사용하십시오. # 2. 세계가 지금 더 아름다운 장소임을 실현. #삼???? # 4 이익. –

+0

대부분의 디버거에서는 정수 변수를 0으로 초기화하므로 정수 배열을 초기화하십시오. – 3bdalla

+0

"나는 c/C++ 프로그램을 만들려고 노력하고있어." 이 두 언어는 서로 다른 언어로 ___are___이 다를 수 있습니다. –

답변

2

공지 코드의 라인 :

int **d = new int*[l2 + 1]; 
for(i=0;i<l1+1;++i) 

당신은 int*(l2 + 1) 수에 대한 메모리를 할당하고 당신은 0 to (l1 + 1)에서 i를 반복하고 있습니다. 따라서 l2 < l1 인 경우 할당하지 않은 메모리에 액세스하고 있습니다.

또한 C++과 C를 섞어 쓰지 마십시오. C 또는 C++를 사용합니다. 의견에서 언급했듯이 C++을 사용할 수 있다면 std::vectorstd::string을 사용하면 두통이 줄어 듭니다. 또한 C++의 IO 클래스를 사용하여 File IO를 수행하고 열려있는 파일을 항상 닫습니다. (예 : C에서는 fclose(file_ptr) 사용).

+0

그래, 어디서 내가 틀렸는 지 알 겠어. 벡터에 대한 약간의 연구와 나는이 문제를 해결할 수 있었다. 정말 고맙습니다. :) – user3508140

0

두 번째 색인에 l2를 사용합니다. 첫 번째 색인이어야하며 두 번째 색인은 l1이어야합니다.

// the edit distance between an empty string and the prefixes of 
// word2 
for (i = 0; i < l1 + 1; i++) { 
    d[0][i] = i; 
} 
+0

Akash가 나를 이길! – sandman

+0

하하. 어쨌든 고맙습니다. :) – user3508140

관련 문제