2013-12-03 03:05 PM
hello everybody!
I need help with my string splitter function. I use stm32f407 and CoIDE for develope. This is the function:char** str_split(char* a_str, const char* a_delim)
{
char** result = 0;
size_t count = 0;
char* tmp = a_str;
char* last_comma = 0;
size_t index;
/* Count how many elements will be extracted. */
while (*tmp)
{
for (index = 0; index < strlen(a_delim); ++index)
{
if (*(a_delim+index) == *tmp)
{
count++;
last_comma = tmp;
}
}
tmp++;
}
/* Add space for trailing token. */
count += last_comma < (a_str + strlen(a_str) - 1);
/* Add space for terminating null string so caller
knows where the list of returned strings ends. */
count++;
result = malloc(sizeof(char*) * count);
if (result)
{
size_t idx = 0;
char* token = strtok(a_str, a_delim);
while (token)
{
assert(idx < count);
*(result + idx++) = strdup(token);
token = strtok(0, a_delim);
}
//assert(idx == count - 1);
*(result + idx) = 0;
}
return result;
}
and this is a part of the code:
tokens = str_split(line, '',;'');
if (tokens)
{
LINScheduleTable[frameIndex].Frame.SignalIDs_lda16[signalIndex] = atoi(*tokens);
LINScheduleTable[frameIndex].Frame.SignalOffsets_lda8[signalIndex] = atoi(*(tokens+1));
for (i = 0; *(tokens + i); i++)
{
free(*(tokens + i));
}
free(tokens);
}
The problem is, the split is working well, but the controller go to default handler when call free. Not in the first call, after 20-30 calls. I think the problem with the pointer, but the code seems good. Anybody have any idea?
Thanks
#string-split-stm32-free
2013-12-03 03:29 PM
Tip : Clear all allocations prior to use either with a memset(), or with calloc(). Filling the structure with deliberately troublesome data will also catch poor initialization elsewhere. With string spaces always over allocate and place a NUL terminator at the end.
Perhaps you are deallocating memory twice, or from a prior instantiation. A common method used to catch malloc/free mismatches is to wrap the functions and mark/track usage.2013-12-03 10:54 PM
You seem to be trying to free portions of the block allocated by malloc - is that allowed?
2013-12-03 10:59 PM
free( *(tokens+i) );
Wait a minute -
free() takes a
pointer argument; you are giving it a
de-referenced pointer!
2013-12-04 12:59 AM
tokens is char** type. So first I free the strings, then free the array.
2013-12-04 01:19 AM
A good habit would be to initialize pointers to zero before *alloc(), reinit them to zero after free(), and check the pointer before trying to free() the associated memory ...
2013-12-04 05:53 AM
''tokens is char** type''
OK - so it is. My bad.
2013-12-04 09:04 AM
Thanks for the help anyone. Tomorrow I try to find the bug.
I'dont know why crash after x calls, and not at the fisrt free call. I see the code many times but i not found bug.