c - 正在重新分配的指针未分配

标签 c pointers memory-management

我想创建一个函数,根据定界符 (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;
}

最佳答案

分配不足 - 按 1。

长度为 Nstring 需要 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。


可能存在其他问题。

关于c - 正在重新分配的指针未分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55929705/

相关文章:

c - 如何用C语言解决C2054问题

c - C 中的输入字符串数组内存管理

c++ - 当 const 指针用作函数的参数时

c - 在不知道大小的情况下输入字符串

java - 继承和对象创建,理论上和实际中

c - 有没有办法在 C 中设置文件指针彼此相等?

c++ - 尝试使用 tcc 针对 gcc 生成的 .o 文件编译源代码时出现奇怪的行为

c++ - 内存操作 malloc 和 free 究竟做了什么?

c - 使用指针访问shm结构

c++ - 当操作系统无法分配内存时,使用 STL 的应用程序是否应该容易发生内存泄漏?