我有一個包含 ip:port 串列的文本,我有一個多執行緒程式,將它們分別拆分為 IP 和埠需要制作 strdup char 指標,這非常煩人我使用了 strchr 但它只給了我埠但不能使用它來提取 IP 目標是將 IP 作為字串提取,將埠提取為整數并且永遠不會分割失敗無論如何
例子:
這是執行緒的啟動函式
void* startthread() {
do {
char* proxy = "127.0.0.1:443";
char* buffered = strdup(proxy);
char* host = strtok(buffered,":");
int port = atoi(strtok(NULL,":"));
printf("%s:%d",host,port);
}while(1);
}
資料庫
Thread 8 "main" received signal SIGSEGV, Segmentation fault.
[Switching to Thread 0x7ffff4a34700 (LWP 47410)]
__GI_____strtol_l_internal (nptr=0x0, endptr=endptr@entry=0x0,
uj5u.com熱心網友回復:
處理此問題的一種相當簡單的方法(與您的標簽保持一致)與 C 和 C 兼容)是使用sscanf:
char host[256];
int port;
sscanf(proxy, "%5[^:]:%d", host, &port);
但是,是的,strtok多執行緒是一個糟糕的組合。然后再次,strtok幾乎任何東西都是一個糟糕的組合。
我想是完整的,我需要指出[^:]掃描格式取決于實作定義的行為。理論上,允許實作按字面意思對待這個——作為^or的意思:,而不是“除了冒號之外的任何東西”——但我知道只有一個實作(Borland 的 MS-DOS 編譯器)這樣做了,它是早已過時。
uj5u.com熱心網友回復:
在這種簡單的情況下,您可以替換strtok為strchr.
void* startthread() {
do {
const char* proxy = "127.0.0.1:443";
char* buffered = strdup(proxy);
if(buffered != NULL) {
char* host = buffered;
int port = 443; // or any useful default value
char* colon = strchr(buffered, ':')
if(colon != NULL) { // found?
*colon = '\0'; // cut off port number from host or IP address
port = atoi(colon 1); // I suggest to use strtol instead of atoi
} // otherwise there is nothing to cut off, and use default port
printf("%s:%d",host,port);
free(buffered);
} else {
// handle error
}
}while(1);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/517048.html
標籤:C细绳多线程标记化
