重新分配的指针未分配

问题描述 投票:1回答:2

我想创建一个函数,根据分隔符(winter-is-coming - > winter | is | coming)将给定字符串分隔为其子字符串,并在双字符指针的末尾返回一个空字符串。当我在C60标准的mac os x下运行这个代码时,我得到第一个字符串为“winter”(〜当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;
}
c pointers memory-management
2个回答
0
投票

分配不足 - 由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。


可能存在其他问题。


0
投票

从第一次看,我怀疑

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

我想你应该有类似的东西

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

那有意义吗?

除此以外

 *(result +c)

没有意义....

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

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

© www.soinside.com 2019 - 2024. All rights reserved.