gpt4 book ai didi

c - C 可执行文件错误

转载 作者:行者123 更新时间:2023-11-30 15:48:04 26 4
gpt4 key购买 nike

我的程序是最新的,并且在 Turbo 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;
}

最佳答案

对 chomp 的调用正在传递未初始化的字符数组。对 strlen 的调用将产生未定义的结果,包括很可能超出缓冲区末尾的读/写。

此后,您调用BoyerMoore,传入这些仍然(至少部分)未初始化的缓冲区。

在此之后,您读取了 patterntarget 但不对它们执行任何操作。

你没有说代码应该做什么,但至少我猜你需要

  • 删除对 chomp 的调用
  • 在调用BoyerMoore之前调用fgets来初始化patterntarget

如果此后不起作用,请尝试使用调试器或添加 printf 语句来跟踪程序进度。

关于c - C 可执行文件错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17038998/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com