【问题标题】:Pointer being reallocated wasn't allocated被重新分配的指针未被分配
【发布时间】:2019-04-30 23:04:35
【问题描述】:

我想创建一个函数,它根据分隔符 (winter-is-coming -> winter|is|coming) 将给定的字符串分隔为其子字符串,并在双字符指针的末尾返回一个空字符串。当我在 C90 标准中的 mac os x 下运行此代码时,我得到第一个字符串为“winter”(~as w, wi, win, wint, winte, winter~ 当我在循环中打印 temp 时)但随后它突然崩溃了并给出这个错误:

untitled2(30275,0x109cf25c0) malloc: *** error for object 0x7fec9a400630: pointer being realloc'd was not allocated
untitled2(30275,0x109cf25c0) malloc: *** set a breakpoint in malloc_error_break to debug

我的代码:

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

char ** split(char *str, char delimeter) {
  int i = 0;
  int c = 0;
  int k = 1;
  char **result;
  result = (char **) malloc(sizeof(char*));
  *result = (char *) malloc(sizeof(char));
  char * temp;
  temp = *result;
  while (str[i] != '\0') {

    if (str[i] != delimeter) {
      *(temp + i) = *(str + i);
      i++;
      temp = (char *) realloc(*(result + c), sizeof(char) * (i + 1));
      continue;
    }

    else {
      c++;
      k++;
      result = (char **) realloc(result, sizeof(char *) * k);

      *(result + c) = (char*) malloc(sizeof(char));
      i++;
      *(temp + i) = '\0';

    }
  }
  printf("%s\n", result[0]);
  return result;
}

int main() {
  char *cpr;
  cpr = (char *) malloc(sizeof(char) * strlen("winter-is-coming"));
  strcpy(cpr, "winter-is-coming");
  printf("%s\n", split(cpr, '-')[0]);
  return 0;
}

【问题讨论】:

  • 如果是NULL,则只能realloc未分配的指针。某些系统会将内存分配归零,但这不是 C 标准定义的。将未初始化的指针传递给realloc 是个坏主意。但在此之前,*(temp+i)=*(str+i); 就出现了问题,它取消了未初始化的指针的引用。
  • 但我最初已经分配了我想在代码开头重新分配的指针(结果)。
  • 它已经为 c=0 分配了,而不是我在 else 语句中需要它时分配它。
  • 您分配了一个双指针,但没有分配您随后取消引用的任何偏移量。
  • (result + c) = (char) malloc(sizeof(char));这条线不是在做那个分配吗?

标签: c pointers memory-management


【解决方案1】:

分配不足 - 1。

长度为N字符串 需要N+1 char。 C 中不需要强制转换。

// cpr = (char *)malloc(sizeof(char)*strlen("winter-is-coming"));
cpr = malloc(strlen("winter-is-coming") + 1);
// Robust code would check for allocation success
if (cpr == NULL) {
  return EXIT_FAILURE;
}
strcpy(cpr,"winter-is-coming");

代码可能无法从split() 返回很好的拆分数指示。以char ** split("", .-) 为例。那么printf("%s\n",result[0]); 也是UB。


可能存在其他问题。

【讨论】:

  • 感谢您的回答,测试数据确保至少有一个分隔符,并且分隔符只有一个字符..
【解决方案2】:

乍一看我很怀疑

result = (char **)malloc(sizeof(char*));

我认为你应该有类似的东西

result = (char **)malloc(MAX_NUMBER_OF_DIFFERENT_SUBSTRINGS * sizeof(char*));

这有意义吗?

否则

 *(result +c)

没有意义....

所以尝试增加分配给结果的内存......

但这可能只是故事的一部分

【讨论】:

  • 这是合理的,但我没有最大子字符串数
  • 只是投入大量,看看它是否有帮助.. ......抱歉,只是一个尝试让事情正常工作的建议......
  • 这段代码的全部意义在于使用动态数组,谢谢
  • @Crazy_39365 好的,-我部分建议添加一个数字以查看是否可以解决问题-或者问题是否在其他地方,但我明白您对使用动态数组的意思。
猜你喜欢
  • 1970-01-01
  • 2018-09-30
  • 2016-08-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-11
  • 2015-07-14
相关资源
最近更新 更多