我正在尝试编写一个代码,用字符“:”分割给定的路径,这是我的代码:
#include <stdio.h>
#include <stdlib.h>
void parser()
{
char ** res = NULL;
char * p = strtok (getenv("PATH"), ":");
int n_spaces = 0, i;
/* split string and append tokens to 'res' */
while (p)
{
res = realloc (res, sizeof (char*) * ++n_spaces);
if (res == NULL)
exit (-1); /* memory allocation failed */
res[n_spaces-1] = p;
p = strtok (NULL, ":");
}
/* realloc one extra element for the last NULL */
res = realloc (res, sizeof (char*) * (n_spaces+1));
res[n_spaces] = 0;
/* print the result */
for (i = 0; i < (n_spaces+1); ++i)
printf ("res[%d] = %s\n", i, res[i]);
/* free the memory allocated */
free (res);
}
int main(int argc , char* argv[])
{
parser();
return 0;
}
此代码在 Linux 中给出了段错误,但是当尝试在 Windows 上运行它时,它工作正常!
最佳答案
您缺少一个包含,即 #include <string.h>
负责为 strtok
提供原型(prototype)您正在使用的功能。缺少原型(prototype)是未定义的行为,不工作不应该让你感到惊讶。
另外(感谢@milevyo 指出了这一点):
您不应该修改 getenv()
返回的指针.
C Standard, Sec. 7.20.4.5, The getenv function
Using getenv()
The return value might be aimed at
a read-only section of memory a single buffer whose contents are modified on each call getenv() returns the same value on each call a dynamically-allocated buffer that might be reallocated on the next call a tightly packed set of character strings with no room for expansion
Use the returned string before calling getenv() again. Do not modify the returned string.
所以通过调用 strtok
给分配了一个指针的变量,该指针已从 getenv()
返回您正在调用其他未定义的行为。
要更正此问题,请复制 getenv()
指针所在的字符串返回的是指向辅助变量 strdup()
关于c - c linux 中的段错误但 windows 中没有,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33257597/