I am struggling with memory allocation. I wanted to enter a string in another, and I made two functions that stopped working in one place - realloc. These features are very similar. First, I copy char to char to a temporary line, and when I try to copy a temporary line to the first, this is the place where I get errors. In the second function, I copy the end of the first line (from a given position) to a temporary line, redistribute the first line (this is where I get errors) and delete everything in me from this position. Then I add a second line and a temporary one for the first line. Here is my code. First function:
void ins (char **str, char *str2, int pos)
{
int len = strlen(str[0]),
len2 = strlen(str2),
i, j, l = 0;
char *s = (char *) malloc ((len + len2) * sizeof(char));
for (i = 0; i < pos; i++)
s[i] = str[0][i];
for (j = 0; j < len2; j++)
s[i + j] = str2[j];
for (int k = pos; k < len; k++)
{
s[i + j + l] = str[0][k];
l++;
}
str[0] = (char *) realloc (str[0], (len + len2) * sizeof(char));
strcpy(str[0], s);
free(s);
s = NULL;
}
Second function:
void ins2 (char **str,char *str2, int pos)
{
int len = strlen(str[0]),
len2 = strlen(str2);
char *s = (char *) malloc ((len - pos) * sizeof(char));
strcpy(s, str[0] + pos);
str[0] = (char *) realloc(str[0], (len + len2) * sizeof(char));
str[0][pos] = '\0';
strcat(str[0], str2);
strcat(str[0], s);
free(s);
s = NULL;
}
source
share