I'm trying to learn C, and one of the things I'm finding tricky is strings and manipulating them. I think I understand the basics of it, but I've taken for granted a lot of what might go into strings in JS or PHP (where I'm coming from).
I'm trying now to write a function that explodes a string into an array, based on a delimiter, using strtok
. Similar to PHP's implementation of explode()
.
Here's the code:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
char **explode(char *input, char delimiter) {
char **output;
char *token;
char *string = malloc(sizeof(char) * strlen(input));
char delimiter_str[2] = {delimiter, '\0'};
int i;
int delim_count = 0;
for (i = 0; i < strlen(input); i++) {
string[i] = input[i];
if (input[i] == delimiter) {
delim_count++;
}
}
string[strlen(input)] = '\0';
output = malloc(sizeof(char *) * (delim_count + 1));
token = strtok(string, delimiter_str);
i = 0;
while (token != NULL) {
output[i] = token;
token = strtok(NULL, delimiter_str);
i++;
}
// if i uncomment this line, output gets all messed up
// free(string);
return output;
}
int main() {
char **row = explode("id,username,password", ',');
int i;
for (i = 0; i < 3; i++) {
printf("%s\n", row[i]);
}
free(row);
return 0;
}
The question I have is why if I try to free(string)
in the function, the output gets messed up, and if I'm doing this incorrectly in the first place. I believe I'm just not mapping out the memory properly in my head and that's why I'm not understanding the issue.
you misunderstand what strtok does, It does not make new strings, it is simply returning a pointer to different parts of the original string. If you then free that string all the pointers you stored become invalid. I think you need
while (token != NULL) {
output[i] = strdup(token);
token = strtok(NULL, delimiter_str);
i++;
}
strdup will allocated and copy a new string for you