c - c linux 中的段错误但 windows 中没有

标签 c linux

我正在尝试编写一个代码,用字符“:”分割给定的路径,这是我的代码:

#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/

相关文章:

c - Linux 中 inet_addr_lst 内核符号的用途是什么?

c - 在 C 中使用 pthread 的线程中的计时器?

linux - 从 linux 交叉编译到 ARM-ELF (ARM926EJ-S/MT7108)

linux - 如何降低 Linux 中 Rails 3 命令的用户时间与系统时间的比率

c - 在 Ansi-C 中导入 Delphi Dll

c - `timer_settime()` 的奇怪行为

c++ - 它怎么可能成为竞争条件。或者我的代码有问题

linux - 在 bash 中截断字符串

linux - 进程间通信

c - 防止内核代码中的双 kfree?