【问题标题】:When I malloc more space for a string within an array of strings, the array of strings duplicates some strings当我为字符串数组中的字符串分配更多空间时,字符串数组会复制一些字符串
【发布时间】:2016-01-21 08:23:14
【问题描述】:

我有一个字符串数组,我正在尝试为其中一个字符串分配更多空间,以便更改字符串的值。

int catenate_strings (char** arr, int index1, int index2) { 
    char *new_string;
    new_string = malloc(1000*sizeof(char));
    if (new_string == NULL) {
        printf("\nError allocating memory\n");
    }   

    strcpy(new_string, arr[index1]);
    strcat(new_string, arr[index2]);
    arr[index1] = new_string;
}

但是,当我运行我的代码时,它会在某些情况下工作,但在其他情况下,它会在 index1 处复制字符串并将其放在 index1 + 1 处。

【问题讨论】:

  • 您是否要“调整”字符串的大小?
  • 请发MCVE
  • 当您执行arr[index1] = new_string 时内存泄漏,您正在丢失之前的字符串。
  • 我正在尝试调整为字符串分配的空间,以便可以在其中放置更长的字符串。
  • 另一种可能是new_string的缓冲区溢出

标签: c arrays string malloc strcpy


【解决方案1】:

您的代码有一些问题:

  1. arr[index1] = new_string 内存泄漏,因为您没有释放旧缓冲区。
  2. 如果结果字符串超过 1000 字节,则缓冲区溢出。
  3. 尽管函数具有返回值 int,但未从 catenate_strings 返回任何值。

如果arr 中的所有条目都使用malloc 分配,那么您可以使用realloc

int catenate_strings (char** arr, int index1, int index2)
{ 
    // Resize buffer to hold old string + new string (+ terminating null byte!)
    char * const new_string = realloc(strlen(arr[index1]) + strlen(arr[index2]) + 1);
    if (new_string == NULL) {
        printf("\nError allocating Memory, cannot resize string\n");
        return -1;
    }   
    strcat(new_string, arr[index2]);
    arr[index1] = new_string;

    return 0;
}

index+1 的重复不是来自显示的代码,而是来自代码中的其他地方。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-04-01
    • 2012-02-22
    • 2013-08-19
    • 2016-03-22
    相关资源
    最近更新 更多