我如何为 char** str 设置一个空值,因为我有错误“解除对越界指针的引用:1 个字节(1 个元素)超过数组 im 使用 C 语言的结尾”
while(part)
{
res = (char**)realloc(res, (i + 1) * sizeof(char*));
*(res + i) = mystrdup(part);
part = mystrdup(strtok(NULL, delim));
i++;
}
res = (char**)realloc(res, i * sizeof(char*));
*(res + i) = NULL; // This is where I Encounter the ERROR
最佳答案
这部分代码
res = (char**)realloc(res, i * sizeof(char*));
*(res + i) = NULL;
通过尝试访问 *(res + i)
,您将前往 off-by-one .你应该写
*(res + i -1) = NULL;
话虽如此,
- Please see this discussion on why not to cast the return value of
malloc()
and family inC
. . - 像
pointerP = realloc (pointerP, .....)
这样的语句被认为是非常不安全的,以防万一,如果realloc()
失败,您将最终也失去了实际的指针。 - 始终根据
NULL
检查malloc()
和函数系列的返回值,以确保成功。 - 另外,在将
strtok()
传递给strdup()
之前,对返回值进行 NULL 检查。
关于c - 如何为 char** str 设置空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34764384/