Wie kann ich free()
von strdup
wenn der Anruf so aussah: *(result + idx++) = strdup(token);
?Wie kann ich frei() nach dem strdup?
Weiterer Kontext:
char **str_split(char *a[], char *a_str, const char a_delim) {
char **result = 0;
size_t count = 0;
char *tmp = a_str;
char *last_comma = 0;
char delim[2];
delim[0] = a_delim;
delim[1] = 0;
/* Count how many elements will be extracted. */
while (*tmp) {
if (a_delim == *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 == NULL) {
printf("Error allocating memory!\n"); //print an error message
return result; //return with failure
}
if (result) {
size_t idx = 0;
char *token = strtok(a_str, delim);
while (token) {
assert(idx < count);
*(result + idx++) = strdup(token); /* memory leak! how to free() */
token = strtok(0, delim);
}
assert(idx == count - 1);
*(result + idx) = 0;
}
return result;
}
'Ergebnis [idx ++]' war zu verständlich, nehme ich an? – Olaf
'delim [0]' und 'delim [1]' werden verwendet, daher sollte der Array-Indexoperator nicht gesperrt werden. – MikeCAT
Der Code, der diese Funktion aufruft, muss auf allen gespeicherten Zeigern "free" aufrufen, sobald er fertig ist. –