我有这个功能:
static void unfoldLines(char **pbuff, char **lines, int foldCount) {
int i, j;
for(i = 1; i <= foldCount; i++) {
removeEOL(lines[i]);
for(j = 0; j < strlen(lines[i]); j++) {
while(isspace(lines[i][j])) {
lines[i]++;
}
}
}
lines[1] = realloc(lines[1], sizeof(char) * (strlen(lines[1]) +
strlen(lines[2]) + 1));
exit(0);
}
lines
它的指针已经在前一个函数中被malloced当我尝试重新定位行[1]时,会出现以下错误:malloc: *** error for object 0x7fcec0404fe1: pointer being realloc'd was not allocated
我知道它已经被malloced了,为什么不能在这个函数中重新分配它呢?
最佳答案
lines[1]
在for循环中递增您应该保留从malloc()
返回的原始指针,并将其与realloc()
一起使用。
此外,realloc()
可能会失败,因此您应该将返回值realloc()
存储在临时指针中,并且只有在成功地将其传输到原始指针时。
关于c - 重新分配在不同函数中分配的指针,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34867753/