您调用 realloc 的方式是错误的。您应该使用临时变量来保存指针,因为如果重新分配失败,您将失去对原始内存块的引用。
char *example(char* input);
int main(void)
{
char *input = malloc(sizeof(*input));
char *tmp;
if((tmp == example(input))) input = tmp;
printf("%s", input);
}
char *example(char* input) {
int i = 0;
char* a = "qweqeqweqweqweqweqwasdfsdfsdgasdgg";
for (int i = 0; i < 20; i++)
{
char *tmp = realloc(input, sizeof(*input) * (i + 2));
if(tmp)
{
input = tmp;
input[i] = a[i];
input[i + 1] = 0;
}
else
{
/* handle allocation error */
}
}
return tmp;
}
您也可以使用指向指针的指针,但您需要保存原始指针以避免潜在的内存泄漏:
int main(void)
{
char *input = malloc(sizeof(*input));
char *tmp = input;
example(&tmp);
if(tmp) input = tmp;
printf("%s", input);
}
void example(char** input) {
int i = 0;
char* a = "qweqeqweqweqweqweqwasdfsdfsdgasdgg";
for (int i = 0; i < 20; i++)
{
*input = realloc(*input, sizeof(*input) * (i + 2));
if(*input)
{
*input = tmp;
(*input)[i] = a[i];
(*input)[i + 1] = 0;
}
else
{
/* handle allocation error */
}
}
}
您的代码中的另一个问题:您不会终止您的字符串。您需要阅读警告。您的代码中有更多问题 - 例如,您在没有原型的情况下调用函数。