[英]Why does memcpy() cause a crash?
我正在尝试运行 Hashq 算法(字符串匹配算法)的实现。 它是为 POSIX 编写的,但我试图在 Windows 上的代码块中运行。
实现是:
#define RANK5 5
#define WSIZE 256 // greater int value fitting in a computer word
#include <stdio.h>
#include <string.h>
int search(unsigned char *x, int m, unsigned char *y, int n) {
int count, i, j, sh, shift[WSIZE], sh1, mMinus1, mMinus4;
unsigned int h;
if (m < 5)
return -1; // substring or pattern has to be greater than 4
/* Preprocessing */
// BEGIN_PREPROCESSING
count = 0;
mMinus1 = m - 1;
mMinus4 = m - 4;
for (i = 0; i < WSIZE; ++i)
shift[i] = mMinus4;
h = x[0];
h = ((h << 1) + x[1]);
h = ((h << 1) + x[2]);
h = ((h << 1) + x[3]);
h = ((h << 1) + x[4]);
shift[h % WSIZE] = m - RANK5;
for (i = RANK5; i < mMinus1; ++i) {
h = x[i - 4];
h = ((h << 1) + x[i - 3]);
h = ((h << 1) + x[i - 2]);
h = ((h << 1) + x[i - 1]);
h = ((h << 1) + x[i]);
shift[h % WSIZE] = mMinus1 - i;
}
h = x[i - 4];
h = ((h << 1) + x[i - 3]);
h = ((h << 1) + x[i - 2]);
h = ((h << 1) + x[i - 1]);
h = ((h << 1) + x[i]);
sh1 = shift[h % WSIZE];
shift[h % WSIZE] = 0;
if (sh1 == 0)
sh1 = 1;
// END_PREPROCESSING
// BEGIN_SEARCHING
i = mMinus1;
memcpy(y + n, x, m);
while (1) {
sh = 1;
while (sh != 0) {
h = y[i - 4];
h = ((h << 1) + y[i - 3]);
h = ((h << 1) + y[i - 2]);
h = ((h << 1) + y[i - 1]);
h = ((h << 1) + y[i]);
sh = shift[h % WSIZE];
i += sh;
}
if (i < n) {
j = 0;
while (j < m && x[j] == y[i - mMinus1 + j])
j++;
if (j >= m) {
count++; // OUTPUT(i-mMinus1);//printf("%d\n", i-mMinus1);count++;//
}
i += sh1;
} else {
// END_SEARCHING;
return count;
}
}
}
int main() {
char *x = "welcometot";
char *y = "welcometotheStack Overflow,welcometoalllearners...welcome!";
int m = strlen(x);
int n = strlen(y);
printf("\n The number of total matching: %d", search(x, m, y, n));
return 0;
}
问题是代码不会生成任何 output 。
hash5.exe
已停止工作
表明:
问题事件名称:APPRCASH
我发现如果memcpy(y+n, x, m);
被删除,代码有效并提供正确的 output? 但是为什么会这样呢? 谁能解释一下?
该算法在以下研究文章中介绍:
S. Faro:基于压缩字母的非常快速的字符串匹配算法,信息和管理中的算法方面 - 第 10 届国际会议,AAIM 2016。会议记录,卷。 9778 计算机科学讲义,Springer,2016 年,第 65-76 页
因为 char *y = "some text" 将被编译/链接过程放置在只读 memory 段中。 尝试使用 char y[] = "some text" 或 char y[SOME_BIGGER_SIZE] = "some text"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.