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]);
}
}
The code aims to find and replace a word (x
) with a second one (y
) in a text dynamically allocated in **p
. They come in a string (sir
) and are separated.
move
stores the difference between the words that are obtained. n
represents the number of lines in the text.
The word x
must not be within another word hence the need to check for the separators.
If the conditions are met then the string is reallocated depending if the move
is positive or negative. If it's positive the string will be longer and can be reallocated for all the apparitions of the word x
inside of it. counter
is a function that counts the apparitions in the string.
When move
is negative the string must be diminished so the reallocation is done after the operations take place.
The replace is done with memmove
and memcpy
.
k
is the position after the apparitions of x
.
During a test there was the need to replace "o"
with "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
.
This is the reference Reference
And this is what I get Result
When replacing "o"
in the middle of the string an error occurs and the pointer to the next line is lost, pointing to the ending part of the previous line. The 1 represents the value of the counter for the line that follows
Does
realloc
use memory that was already allocated and by doing so the next pointer is lost?
EDIT: Here is the allocation of the array:
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);
q
,p
, andx
are self-explanatory! It could probably be deciphered in less than an hour. – Millie Smith Dec 7 '15 at 23:20