A
Alia K
I followed some of the advice on this page (http://efreedom.com/
Question/1-3142365/Combine-Directory-File-Path-C) to rewrite a path
combine functions as below. Even though it seems to work, I suspect
I'm doing something wrong because (1) I am not including the
possibility of the "/" length in malloc and (2) I am probably causing
a memory leak because the pointer returned by malloc is not freed.
Now, because it seems to work ok (no complaints with gcc or clang -
Wall) I'm unsure whether it's a good function or not (-:
Any advice would be appreciated. Please find the function below:
<code>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
char *combine(const char *path1, const char *path2)
{
char *destination = malloc(
strlen(path1) + strlen(path2));
if (path1 == NULL && path2 == NULL) {
strcpy(destination, "");
} else if (path2 == NULL || !path2[0]) {
strcpy(destination, path1);
} else if (path1 == NULL || !path1[0]) {
strcpy(destination, path2);
} else {
char directory_separator[] = "/";
const char last_char = path1[strlen(path1) - 1];
strcpy(destination, path1);
if (last_char != directory_separator[0])
strcat(destination, directory_separator);
strcat(destination, path2);
}
return destination;
}
int main(int argc, char **argv)
{
printf("res: %s\n", combine("path1", "path2"));
return EXIT_SUCCESS;
}
</code>
Thank you.
AK
Question/1-3142365/Combine-Directory-File-Path-C) to rewrite a path
combine functions as below. Even though it seems to work, I suspect
I'm doing something wrong because (1) I am not including the
possibility of the "/" length in malloc and (2) I am probably causing
a memory leak because the pointer returned by malloc is not freed.
Now, because it seems to work ok (no complaints with gcc or clang -
Wall) I'm unsure whether it's a good function or not (-:
Any advice would be appreciated. Please find the function below:
<code>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
char *combine(const char *path1, const char *path2)
{
char *destination = malloc(
strlen(path1) + strlen(path2));
if (path1 == NULL && path2 == NULL) {
strcpy(destination, "");
} else if (path2 == NULL || !path2[0]) {
strcpy(destination, path1);
} else if (path1 == NULL || !path1[0]) {
strcpy(destination, path2);
} else {
char directory_separator[] = "/";
const char last_char = path1[strlen(path1) - 1];
strcpy(destination, path1);
if (last_char != directory_separator[0])
strcat(destination, directory_separator);
strcat(destination, path2);
}
return destination;
}
int main(int argc, char **argv)
{
printf("res: %s\n", combine("path1", "path2"));
return EXIT_SUCCESS;
}
</code>
Thank you.
AK