簡體   English   中英

帶有字符指針的 strsep() 在 c 中給出分段錯誤

[英]strsep() with char pointer gives segmentation fault in c

int main() {
  char* instruction = "x10,   14(x2)";
  char* rd = strsep(&instruction, ",");
  printf("%c", *rd);
    
  return(0);
}

我試圖運行這幾行,我希望它打印“x”,但它給出了分段錯誤。 我做錯了什么?

strsep 人

 char *strsep(char **stringp, const char *delim); If *stringp is NULL, the strsep() function returns NULL and does nothing else. Otherwise, this function finds the first token in the string *stringp, that is delimited by one of the bytes in the string delim. This token is terminated by overwriting the delimiter with a null byte ('\\0'), and *stringp is updated to point past the token. In case no delimiter was found, the token is taken to be the entire string *stringp, and *stringp is made NULL.

您正試圖通過將其傳遞給strsep來修改僅就緒的字符串。

  char* instruction = "x10,   14(x2)";
  char* rd = strsep(&instruction, ",");

嘗試

  char* instruction = "x10,   14(x2)";
  char *temp = strdup(instruction);
  char *save = temp;
  char* rd = strsep(&temp, ",");
  free(save);

您需要保留指向temp的指針的副本,以便以后可以將其釋放。

示例:來自描述“ stringp 已更新為指向令牌之后。” 如果您使用free(temp) ,你會經過一個無效的地址, free()因為temp不再指向分配塊的某處點在它的內部的開始。

暫無
暫無

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

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