簡體   English   中英

c linux中但不是在Windows中的分段錯誤

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

我正在嘗試編寫一個代碼,以字符“:”分割給定的路徑,這是我的代碼:

#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函數提供原型。 為此,缺少原型是不確定的行為,不應讓您驚訝而不工作。

另外(指向@milevyo指出這一點):

您不應該修改getenv()返回的指針beeing。

C標准,秒 7.20.4.5,getenv函數

使用getenv()

返回值可能針對

 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 

再次調用getenv()之前,請使用返回的字符串。 不要修改返回的字符串。

因此,通過將strtok調用給已分配了從getenv()返回的指針的變量,您正在調用其他未定義的行為。

要解決此問題,請使用strdup()getenv()返回的指針指向的字符串復制到輔助變量中

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM