簡體   English   中英

C分割字符串時出現分段錯誤

[英]C Segmentation fault when spitting a string

首先,很抱歉,如果我這是一個基本的(或愚蠢的)問題,我來自Python,而我在C語言方面還是一個新手(仍然在研究它)。

我有一個簡短的腳本,用於將字符串拆分為子字符串,例如:“ this is my -string”分解為“ this”,“ is”,“ my”,“-string”。

之后,我要選擇以char:'-'開頭的子字符串,並保存在一個名為“ subline”的變量中:

#include <stdio.h>
#include <string.h>

#define MAX_CHAR 9999

int main ()
{

  char line[] ="this is my -string";
  char *p;
  char subline[MAX_CHAR];


  printf ("Split string in tokens:\n");

  p = strtok (line," ");

  while (p != NULL)
  {
    printf ("%s\n", p);
    p = strtok (NULL, " ,");

    if ((strncmp(p, "-", 1) == 0)){ 
      memcpy(subline, ++p, strlen(p)+1);
      printf ("subline: %s\n", subline);

    }


  }
  printf ("\nData:\n");
  printf ("subline is: %s\n", subline);
  return 0;
}

在while循環內,一切運行良好,我什至可以打印變量“ subline”,但是在while循環外,我遇到了分段錯誤,這是輸出:

root@debian:/home/user/Desktop/splits# ./split
Split string in tokens:
this
is
my
subline: string
string
Segmentation fault

我試圖找出並使用malloc(sizeof(* subline))解決了它; 但在while循環外始終存在相同的分段錯誤。

有人知道嗎?

謝謝。

p變為null時,您仍將其傳遞給strcncmp() 不要那樣做-而是添加另一個檢查。

當代碼在while循環中檢測到沒有更多匹配項時, strtok將返回NULL,但是在循環邏輯捕獲到該strncmp()之前,將使用NULL指針調用strncmp()方法。

這是主要錯誤:

在處理第一個字符串指針之前,第二次調用函數strtok()

這行:

memcpy(subline, ++p, strlen(p)+1);

(請記住,“ p”是指向字符串第一個字符的指針,由於某些“副作用”,在memcpy()函數內部對該指針進行預遞增是一個非常糟糕的主意。

#include <stdio.h>
#include <string.h>

// wrap numerics in parens to avoid certain 'text replacement' errors
#define MAX_CHAR (9999)

int main ( void )
{

  char line[] ="this is my -string";
  char *p;
  char subline[MAX_CHAR] = {'\0'};  // assure the string will be properly terminated


  printf ("Split string in tokens:\n");

  p = strtok (line," "); // p now points to first token (or contains NULL

  while (p)   // will continue to loop while p not equal to NULL, where NULL is the same as 'false'
  {
      printf ("%s\n", p);

      // don't need all this power function call
      // if ((strncmp(p, "-", 1) == 0))
      if( '-' == p[0] )
      {
          p++; // step past the '-'
          memcpy(subline, p, strlen(p)); // remember, subline is init. to all '\0'
          printf ("subline: %s\n", subline);
      }

      p = strtok (NULL, " ,"); // p now points to next token (or contains NULL)
  } // end while

  printf ("\nData:\n");
  printf ("subline is: %s\n", subline);
  return 0;
}

暫無
暫無

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

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