首页 > 解决方案 > C: Realloc 无效指针?

问题描述

这是我在学校的任务:编写一个函数 insertString ,将字符串 s2 插入到 s1 的索引 n.s1 已使用 malloc 分配并应调整大小(该函数再次为 void)。

该程序在 PC 上给了我一个 NULL,当我切换到手机时,编译器说我的 realloc 指针无效。但我真的不知道我做错了什么。

这是代码:

void insertString(char *str1, char *str2, int n){
    int lengStr2=strlen(str2);
    printf("%d %d ", lengStr2,n);
    printf("\nstr1= %s, str2: %s, n: %d ",str1,str2,n);
    str1=(char*)realloc(str1,lengStr2+n+1);
    if (str1==NULL){
        printf("Error\n");
        free(str1);
        return -1;
    }
        printf("\nstr1= %s, str2: %s, n: %d ",str1,str2,n);
    memcpy(str1+n,str2,lengStr2+1);
        printf("\nstr1= %s, str2: %s, n: %d ",str1,str2,n);
}
void testInsertString( char *str2, int n, char *expect){
    char*str1=(char*)malloc(3*sizeof(char));
    str1="hoi";
    printf("\nstr1= %s, str2: %s, n: %d ",str1,str2,n);
    insertString(str1,str2,n);
    printf("--> result:%s --> ",str1);
    (strcmp(str1,expect)==0)?printf("Success"): printf("Failure");
    free(str1);
    printf("\nIs Free\n");
}

这里的输出:

str1= hoi, str2: Hallo, n: 1 5 1
str1= hoi, str2: Hallo, n: 1 Error
--> result:hoi --> Failure
Is Free

Process returned 0 (0x0)   

请问如果你知道我做错了什么,你能告诉我正确的版本吗?即便如此,我也有一个问题,即我不能仅仅通过阅读文本来正确地编写程序,我需要看看它应该如何编写。所以我需要看到正确的结果才能从错误中吸取教训^^”(这就是为什么学校里的一些东西对我来说真的很难)。提前谢谢^^

标签: cpointersdynamic-memory-allocationreallocinvalid-pointer

解决方案


char *str1 = malloc(3*sizeof(char));  /* Allocate memory */
str1="hoi";       /* Discard the only reference to the allocated memory */

上述两行在精神上类似于:

诠释 x = 5; x = 7;

您需要将字符串“hoi”复制到新分配的内存中,并且需要分配至少4 个字节来保存字符串“hoi”。例如:

char *hoi = "hoi";
char *str1 = malloc(strlen(hoi) + 1);
if( str1 == NULL ){
    perror("malloc");
    exit(EXIT_FAILURE);
}
sprintf(str1, "%s", hoi);

推荐阅读