【发布时间】: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