2017-07-19 61 views
0

我想标记一个字符串,并插入一个标记作为键和其余作为地图的值。但是在插入时,我会遇到分段错误。我调试了很长时间,但找不到解决此错误的方法。这里是我的代码:令牌化字符串时的分段错误

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; 
    } 
} 

任何帮助将不胜感激!

+1

''而只能在心碎结束(fin.eof()!)。测试读取是否失败,而不是读取之前,因此您不处理错误的数据。 https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong –

+0

为什么你不使用'std :: string',或者至少,存储' std :: string'在地图中? – PaulMcKenzie

回答

1

经过进一步调试,我找出了确切的问题。在将它们与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; 
    } 
} 
+1

现在,你所要做的就是找出[为什么'while(fin.feof())'总是一个bug](https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-一个循环条件考虑的,是错误的)。 –