I need to return a char** but when I try to do this, the compiler tells me that I want to return the address of a local variable. How can I do that? I know that I should allocate space for this variable but how? Here is my code, but the second printf doesn’t appear and the function returns nothing:
char** parse_cmd(const char* cmdline) {
char** arguments = (char**)malloc(100);
int i;
int j=0, k=0;
printf("%s\n", cmdline);
for(i=0; i<100; i++) {
arguments[i] = malloc(100);
}
for(i = 0; i < strlen(cmdline); i ++) {
if(cmdline[i] != ' ') {
arguments[j][k] = cmdline[i];
k++;
} else {
arguments[j][k] = '\0';
j++;
k = 0;
}
}
printf("%s\n", arguments[1]);
return arguments;
}
Here’s the code I assembled – and tested. It uses dynamic memory allocation for both the
argvargument list and for each argument as it is assembled. The functionrelease_cmd()releases the allocated space. The functioncleanup()is internal and releases allocated space on a failure, before returning a null double-pointer. This simplifies the error handling. There’s a minimal test harness in theprompt()function andmain(). I haven’t run in undervalgrind, but the MacOS X implementation ofmalloc()quite often spots problems so I’m moderately confident there’s no gross memory abuse – but there could be an off-by-one leak. I haven’t tested thecleanup()code by faking an allocation failure.