realloc():无效指针已中止(核心已转储)
realloc(): invalid pointer Aborted (core dumped)
我正在努力创建一个类似于 bash 的 shell。在尝试获取与命令关联的参数(即 ls -l)时,我 运行 出错了。我在网上搜索过,没有找到任何有用的东西。
char *userInCopy;
char *ret;
userInCopy = (char*)calloc(1024, sizeof(char));
ret = (char*)calloc(64, sizeof(char));
strcpy(userInCopy, userIn);
int i = 0;
while((ret = strsep(&userInCopy, " "))){
*(args + i) = (char*)calloc(strlen(ret), sizeof(char));
strcpy((*(args+i)), ret);
i++;
ret = (char*) realloc(ret, (64)* sizeof(char));
}
我在 char userIn 中获得了用户的输入,并且分配正确。然后,我使用 strsep 分别获取每个参数来解析输入。我可以获得 ls 参数和 -l 参数,但是当它在 -l 之后转到 realloc 时,它会给我 "realloc(): invalid pointer" 错误。我不知道为什么这会在获得 ls 参数后第一次起作用,但在获得 -l 参数后失败。有什么建议吗?
问题是您正在用 strsep
return 值覆盖 ret
。
while((ret = strsep(&userInCopy, " "))) //Here
有另一个临时变量存储 strsep
return.
void *realloc(void *ptr, size_t size);
ptr
must have been returned by an earlier call to malloc(), calloc()
or realloc().
我正在努力创建一个类似于 bash 的 shell。在尝试获取与命令关联的参数(即 ls -l)时,我 运行 出错了。我在网上搜索过,没有找到任何有用的东西。
char *userInCopy;
char *ret;
userInCopy = (char*)calloc(1024, sizeof(char));
ret = (char*)calloc(64, sizeof(char));
strcpy(userInCopy, userIn);
int i = 0;
while((ret = strsep(&userInCopy, " "))){
*(args + i) = (char*)calloc(strlen(ret), sizeof(char));
strcpy((*(args+i)), ret);
i++;
ret = (char*) realloc(ret, (64)* sizeof(char));
}
我在 char userIn 中获得了用户的输入,并且分配正确。然后,我使用 strsep 分别获取每个参数来解析输入。我可以获得 ls 参数和 -l 参数,但是当它在 -l 之后转到 realloc 时,它会给我 "realloc(): invalid pointer" 错误。我不知道为什么这会在获得 ls 参数后第一次起作用,但在获得 -l 参数后失败。有什么建议吗?
问题是您正在用 strsep
return 值覆盖 ret
。
while((ret = strsep(&userInCopy, " "))) //Here
有另一个临时变量存储 strsep
return.
void *realloc(void *ptr, size_t size);
ptr
must have been returned by an earlier call to malloc(), calloc() or realloc().