0

此函数从用户那里获取分配的内存输入(大小:1 字节)并将其放入堆数据中。它在功能上正常工作,但是当此功能结束并返回主功能时,输入将被破坏。当重新分配函数更改堆内存中字符串的地址时会发生这种情况。谁能帮我修复它?

int main() {
    char* input = (char*)malloc(sizeof(char));
    example(input);
    printf("%s", input);
}

   
void example(char* input) {
    int i = 0;
    char* a = "qweqeqweqweqweqweqwasdfsdfsdgasdgg";
    for (int i = 0; i < 20; i++) {
        input = (char*)realloc(input, sizeof(char) * i + 1);
        input[i] = a[i];
    }
}
4

2 回答 2

2

realloc函数可以返回一个与传入的指针不同的指针。如果发生这种情况,inputmain函数中的副本无效。

您可以通过返回修改后的指针并在函数中example分配回来解决此问题。还:inputmain

  • 不要强制转换的返回值realloc
  • 如果realloc失败原始指针仍然有效,所以分配一个临时的并检查返回值
  • 您需要向字符串添加终止空字节并为其分配额外空间。

所以你的功能会变成这样:

char *example(char* input) {
    int i = 0;

    char* a = "qweqeqweqweqweqweqwasdfsdfsdgasdgg";
    for (int i = 0; i < 20; i++) {
        char *tmp = realloc(input, i + 1 + 1);
        if (!tmp) {
            perror("relloc failed");
            free(input);
            exit(1);
        }
        input = tmp;
        input[i] = a[i];
    }
    intput[i] = 0;
    return input;
}

你这样称呼它:

input = example(input);

您还应该将定义example移至 before main,这样才能正确调用它。

于 2021-01-30T19:43:18.310 回答
1

您调用 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 */
        }
    }
}

您的代码中的另一个问题:您不会终止您的字符串。您需要阅读警告。您的代码中有更多问题 - 例如,您在没有原型的情况下调用函数。

于 2021-01-30T19:56:38.677 回答