2013-06-11 4 views
0

Моя программа обновлена ​​и отлично работает, когда я запускаю Turbo C. После компиляции и запуска программы создается исполняемый файл. Когда я запускаю исполняемый файл, он должен работать, но для следующей программы он всегда дает «ложный» ответ.Ошибка в C исполняемом файле

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

char *BoyerMoore(unsigned char *data, unsigned int dataLength, unsigned char *string, unsigned int strLength) 
{ 
    unsigned int skipTable[256], i; 
    unsigned char *search; 
    register unsigned char lastChar; 

    if (strLength == 0) 
    return NULL; 

    // Initialize skip lookup table 
    for (i = 0; i < 256; i++) 
    skipTable[i] = strLength; 

    search = string; 

    // Decrease strLength here to make it an index 
    i = --strLength; 

    do 
    { 
    skipTable[*search++] = i; 
    } while (i--); 

    lastChar = *--search; 

    // Start searching, position pointer at possible end of string. 
    search = data + strLength; 
    dataLength -= strLength+(strLength-1); 

    while ((int)dataLength > 0) 
    { 
    unsigned int skip; 

    skip = skipTable[*search]; 
    search += skip; 
    dataLength -= skip; 
    skip = skipTable[*search]; 
    search += skip; 
    dataLength -= skip; 
    skip = skipTable[*search]; 

    if (*search != lastChar) /*if (skip > 0)*/ 
    { 
     // Character does not match, realign string and try again 
     search += skip; 
     dataLength -= skip; 
     continue; 
    } 

    // We had a match, we could be at the end of the string 
    i = strLength; 

    do 
    { 
     // Have we found the entire string? 
     if (i-- == 0) 
     return search; 
    } while (*--search == string[i]); 

    // Skip past the part of the string that we scanned already 
    search += (strLength - i + 1); 
    dataLength--; 
    } 

    // We reached the end of the data, and didn't find the string 
    return NULL; 
} 
void chomp(char *s) { 
    int n = strlen(s); 
    while (n && (s[n-1]==10 || s[n-1]==13)) s[--n] = 0; 
} 
int main(void) 
{ 
    char target[200]; 
    char *ch = target,*str; 
    char pattern[20]; 
    int i,k,count,l; 
    chomp(target); 
    chomp(pattern); 
    str = BoyerMoore(target, strlen(target), pattern, strlen(pattern)); 
    printf("Enter the string: \n"); 
    fgets(target,100,stdin); 
    //scanf ("%[^\n]%*c", target); 
    printf("Enter the string to be matched: \n"); 
    fgets(pattern,20,stdin); 
    //scanf ("%[^\n]%*c", pattern); 


    if (str == NULL) 
    puts("String not found"); 
    else 
    puts("true"); 
    getch(); 
    return 0; 
} 
+3

Это называется семантической ошибкой. Вы пытались запустить код в отладчике, чтобы получить информацию о его состоянии в определенных точках выполнения? Это наверняка поможет. –

ответ

1

Вызовы chomp которые пропускают массивы неиницализированные символов. Затем вызовы strlen будут иметь неопределенные результаты, в том числе, возможно, чтение/запись за пределами ваших буферов.

После этого вы вызываете BoyerMoore, передавая в них все еще (по крайней мере частично) неинициализированные буферы.

После этого вы читаете pattern и target, но ничего не делайте с ними.

Вы не говорите, что код должен делать, но по крайней мере я думаю, что вам нужно

  • удалить вызовы chomp
  • вызова fgets инициализацию pattern и target перед вызовом BoyerMoore

Если после этого не работают, попробуйте использовать отладчик или добавьте операторы printf для отслеживания прогресса программы.

Смежные вопросы