I am trying to tokenize a string and insert one token as the key and the rest as values of a map. But while inserting, I get a segmentation fault. I debugged for a long time but could not find a way to overcome this error. Here is my code:
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;
}
}
Any help would be appreciated!