void operation2(char **p, int n, char *sir) {
int i, move, k, xlen, ylen;
char *x, *y, *q, separatori[] = " \'\",!?";
x = strtok(sir, " ");
y = strtok(NULL, " ");
xlen = strlen(x);
ylen = strlen(y);
move = ylen - xlen;
for (i = 0; i < n; i++) {
k = 0;
while (strstr(p[i] + k, x)) {
q = strstr(p[i] + k, x);
if ((strchr(separatori, *(q - 1)) || q == p[i]) &&
(*(q + xlen) == '\0' || strchr(separatori, *(q + xlen)))) {
if (move > 0 && k == 0)
p[i] = realloc(p[i], (strlen(p[i]) + move * counter(p[i], x) + 1) * sizeof(char));
q = strstr(p[i] + k, x);
memmove(q + xlen + move, q + xlen, strlen(q + xlen) + 1);
memcpy(q, y, ylen);
k = strlen(p[i]) - strlen(q) + ylen;
if (move < 0)
p[i] = realloc(p[i], (strlen(p[i]) + move + 1) * sizeof(char));
} else
k = k + xlen;
}
puts(p[i]);
}
}
该代码旨在在 x
中动态分配的文本中查找一个词 ( y
) 并将其替换为第二个词 ( **p
) .它们以字符串形式出现 ( sir
) 并且是分开的。
move
存储获得的单词之间的差异。 n
表示文本中的行数。
单词x
不能在另一个词中,因此需要检查分隔符。
如果满足条件,则根据 move
是否重新分配字符串。是正面的还是负面的。如果它是正数,字符串会更长并且可以重新分配给单词 x
的所有出现。在里面。 counter
是一个计算字符串中出现次数的函数。
当move
为负数,则必须减少字符串,以便在操作发生后重新分配。
替换是用 memmove
完成的和 memcpy
.
k
是x
出现后的位置.
在测试期间需要替换 "o"
与 "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
.
这是引用 Reference
这就是我得到的 Result
替换"o"
时在字符串的中间发生错误,指向下一行的指针丢失,指向上一行的结尾部分。 1 表示后续行的计数器值
Does
realloc
use memory that was already allocated and by doing so the next pointer is lost?
编辑:这是数组的分配:
int n, i;
scanf("%d", &n);
char **p, *aux;
p = malloc(n * sizeof(char *));
aux = malloc(12000 * sizeof(char));
getchar();
for (i = 0; i < n; i++) {
fgets(aux, 12000, stdin);
p[i] = malloc((strlen(aux) + 1) * sizeof(char));
strcpy(p[i], aux);
p[i][strlen(p[i]) - 1] = '\0';
}
free(aux);
最佳答案
您的代码非常困惑,因为副作用太多,对 strlen
的冗余调用...
主要问题是您没有为字符串分配足够的空间:您忘记了 '\0'
终止符所需的额外字节。
您在解析文件时在主例程中犯了这个错误。
当你realloc
吃掉这条线时,你又做了一次。
当您memmove
该行的内容时,您也忘记了包含空字节。
首先解决这些问题。可能还有其他的,但您需要简化代码才能看到它们。阅读所有评论,有很多提示。
编辑:您已将代码固定到位,这可能会使这个问题的其他读者感到困惑,但您在第二次调用 realloc
时仍然有错误:
p[i] = realloc(p[i], (strlen(p[i]) + move + 1) * sizeof(char));
不正确,因为您已经缩短了该行,因此 strlen(p[i])
是新的长度。简单地写:
p[i] = realloc(p[i], strlen(p[i]) + 1);
编辑:这是 operation2
的简单版本,修复了评论中的大多数评论。我没有使用 count
,因为您没有发布代码,所以我不能断言这样做是正确的。
void operation2(char **p, int n, char *sir) {
int i, move, k, xlen, ylen;
static const char separatori[] = " \'\",!?";
char *x, *y, *q;
x = strtok(sir, " ");
y = strtok(NULL, " ");
xlen = strlen(x);
ylen = strlen(y);
move = ylen - xlen;
for (i = 0; i < n; i++) {
k = 0;
while ((q = strstr(p[i] + k, x)) != NULL) {
k = q - p[i];
if ((q == p[i] || strchr(separatori, q[-1])) &&
(q[xlen] == '\0' || strchr(separatori, q[xlen]))) {
if (move > 0) {
p[i] = realloc(p[i], strlen(p[i]) + move + 1);
q = p[i] + k;
}
memmove(q + ylen, q + xlen, strlen(q + xlen) + 1);
memcpy(q, y, ylen);
k += ylen;
if (move < 0) {
p[i] = realloc(p[i], strlen(p[i]) + 1);
}
} else {
k += xlen;
}
}
puts(p[i]);
}
}
关于c - 使用 realloc 后,数组中的下一个指针丢失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34144986/