简体   繁体   English

c linux中但不是在Windows中的分段错误

[英]segmentation fault in c linux but not in windows

I am trying to write a code to split given Path by the character ":" and there is my code : 我正在尝试编写一个代码,以字符“:”分割给定的路径,这是我的代码:

#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;
}

this code gives me segmentation fault in linux but when a tried to run it on windows , it worked fine !! 这段代码给了我Linux的分段错误,但是当尝试在Windows上运行它时,它运行良好!

You are missing an include, namely #include <string.h> which is responsible for providing the prototype for the strtok function you are using. 您缺少一个包含,即#include <string.h> ,该包含负责为您使用的strtok函数提供原型。 Missing the prototype for this is undefined behaviour, and should not surprise you to not work. 为此,缺少原型是不确定的行为,不应让您惊讶而不工作。

Additionally (credit to @milevyo for pointing this out): 另外(指向@milevyo指出这一点):

You are not supposed to modify the pointer beeing returned by getenv() . 您不应该修改getenv()返回的指针beeing。

C Standard, Sec. C标准,秒 7.20.4.5, The getenv function 7.20.4.5,getenv函数

Using getenv() 使用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. 再次调用getenv()之前,请使用返回的字符串。 Do not modify the returned string. 不要修改返回的字符串。

So by calling strtok to a variable assigned a pointer that has been returned from getenv() you are invoking additional undefined behaviour. 因此,通过将strtok调用给已分配了从getenv()返回的指针的变量,您正在调用其他未定义的行为。

To correct this, copy the string that the pointer which getenv() returned is pointing to into an auxiliary variable with strdup() 要解决此问题,请使用strdup()getenv()返回的指针指向的字符串复制到辅助变量中

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM