[英]Segmentation fault while tokenizing string
我試圖標記一個字符串,並插入一個標記作為鍵,其余的作為映射的值。 但是在插入時,出現了段錯誤。 我調試了很長時間,但是找不到解決此錯誤的方法。 這是我的代碼:
while (!fin.eof())
{
char *str1;
char buf[MAX_CHARS_PER_LINE];
fin.getline(buf, MAX_CHARS_PER_LINE);
str1 = new char[strlen(buf)];
int n = 0;
char *token[MAX_TOKENS_PER_LINE] = {};
token[0] = strtok(buf, DELIMITER);
if (token[0])
{
for (n = 1; n < MAX_TOKENS_PER_LINE; n++)
{
token[n] = strtok(0, DELIMITER);
if (!token[n]) break;
}
}
// Forming str1 using the tokens here
strcpy(str1, token[0]);
strcat(str1, ":");
strcat(str1, token[1]);
int key = atoi(token[3]);
// Adding str1 to map
nameId[key] = str1;
}
}
任何幫助,將不勝感激!
經過進一步調試,我找出了確切的問題。 在將它們與str1連接之前,我沒有檢查令牌是否為NULL
。 強制執行該檢查后,str1始終獲取有效值,因此將其插入到映射中。
這是我更新的代碼:
while (!fin.eof())
{
char *str1;
char buf[MAX_CHARS_PER_LINE];
fin.getline(buf, MAX_CHARS_PER_LINE);
str1 = new char[strlen(buf)];
int n = 0;
char *token[MAX_TOKENS_PER_LINE] = {};
// Enforcing NULL check for buf
if (buf)
{
token[0] = strtok(buf, DELIMITER);
}
// Enforcing the NULL check for the tokens
if (token[0])
{
for (n = 1; n < MAX_TOKENS_PER_LINE; n++)
{
token[n] = strtok(0, DELIMITER);
if (!token[n]) break;
}
pair<map<int, char *>::iterator, bool> result;
// Forming str1 using the tokens here
strcpy(str1, token[0]);
strcat(str1, ":");
strcat(str1, token[1]);
// Adding str1 to map
int key = atoi(token[3]);
nameId[key] = str1;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.