【问题标题】:C: Realloc invalid pointer?C: Realloc 无效指针?
【发布时间】:2021-04-18 22:36:53
【问题描述】:

这是我在学校的任务: 编写一个函数​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)   

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

【问题讨论】:

  • str1 是一个字符串文字。它不能被重新分配。在str1=malloc(...)之后,需要用sprintfstrcat之类的方式将数据复制到str1。重新分配str1="hoi" 会丢弃您分配的内存地址。这是内存泄漏。
  • 考虑将-Wwrite-strings 添加到编译器标志;这将导致它警告str1="hoi"
  • OT:关于:int lengStr2=strlen(str2); 函数:strlen() 返回 size_t(无符号值)而不是 int
  • 在函数中:void insertString(char *str1, char *str2, int n){ 这个函数被声明(通过void)不返回值,但是,该函数包含:return -1; 编译时,总是启用警告,然后修复那些警告。 (对于gcc,至少使用:-Wall -Wextra -Wconversion -pedantic -std=gnu11)注意:其他编译器使用不同的选项来产生相同的结果
  • 关于:str1=(char*)realloc(str1,lengStr2+n+1); if (str1==NULL){ printf("Error\n"); free(str1); return -1; 1) 调用时:realloc() 始终分配给“临时”变量。否则,当函数失败时,原来的指针丢失(导致内存泄漏) 2)错误信息应该输出到stderr,而不是stdout 建议使用:perror( "realloc failed" ); 3)返回的类型是void*可以分配给任何指针。强制转换只会使代码混乱(并且容易出错)

标签: c pointers dynamic-memory-allocation realloc invalid-pointer


【解决方案1】:

这是一个固定版本:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

// Changing the signature to return the reallocated ptr would be safer
char * insertString(char *str1, char *str2, int n){
    int lengStr2=strlen(str2);

    //because str1 could differ from the received ptr after reallocation
    str1=(char*)realloc(str1,lengStr2+n+1); 
    if (str1==NULL){
        printf("Error\n");
        return NULL;
    }
    strcpy(str1+n,str2);
    return str1; // So we return the new ptr to the caller
}
void testInsertString( char *str2, int n, char *expect){
    char*str1=(char*)malloc(6*sizeof(char)); // The null termination must be counted
    strcpy(str1, "Hello");                   // You should use strCpy here instead of =
    str1 = insertString(str1,str2,n);        // Refreshes the ptr
    printf("\n--> result:%s --> ",str1);
    (strcmp(str1,expect)==0)?printf("Success"): printf("Failure");
    free(str1);
}

int main() {
    testInsertString(" World", 5, "Hello World"); // --> result:Hello World --> Success
    return 0;
}

【讨论】:

【解决方案2】:
char *str1 = malloc(3*sizeof(char));  /* Allocate memory */
str1="hoi";       /* Discard the only reference to the allocated memory */

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

int 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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-16
    • 1970-01-01
    • 2015-07-13
    • 1970-01-01
    相关资源
    最近更新 更多