I need to write a function in C that, given a path such as /usr/bin/wc
, returns the parent directory of the file (this one would return /usr/bin
). This is my attempt at doing this:
char *get_parent_dir(char *path) {
char *head = path;
int i = strlen(path) - 1;
while (i > 0) {
if (path[i] == '/') {
path[i] = '\0';
break;
}
i--;
}
return head;
}
However, upon running this with a test path, I get the following error: Bus error: 10
.
Can anyone explain why this is, and what I could change to avoid getting this error?
Edit: my usage of the function is something like
char *full_path = "/usr/bin/wc";
get_parent_dir(full_path);