There are multiple problems in your code:
- why do you allocate space for 5 pointers but only use 4?
- why do you allocate 10 bytes for
str
, copy a string to it, duplicate that and free str for every iteration?
- you do not allocate space for the null terminator in the copy of
"Maneger"
.
- you do not free the strings in
li
.
- you do not check for potential
malloc
failures.
Here is a corrected version:
#include <stdlib.h>
#include <string.h>
void free_test(char **a) {
if (a) {
for (int i = 0; a[i]; i++) {
free(a[i]);
}
free(a);
}
}
char **test(void) {
char **res = malloc(sizeof(*res) * 4);
if (res) {
int cur;
for (cur = 0; cur < 3; cur++) {
res[cur] = strdup("Maneger");
if (res[cur] == NULL) {
free_test(res);
return NULL;
}
}
res[cur] = NULL;
}
return res;
}
int main(int argc, char *argv[]) {
char **li = test();
if (li == NULL)
return 1;
//some code
free_test(li);
return 0;
}
strdup()
is a much simpler and safer way to duplicate strings. It is not part of Standard C, but supported on Posix and other systems. If it is not available on your system, it can be redefined this way:
char *strdup(const char *s) {
size_t len = strlen(s);
char *p = malloc(len + 1);
if (p != NULL) {
memcpy(p, s, len + 1);
}
return p;
}