Reputation: 269
Why I cannot get "xxx"? The returned value is something very strange symbols... I want the returned value to be xxx, but I don't know what is wrong with this program. The function works well and can print "xxx" for me, but once it returns value to main function, the string outcome just cannot display "xxx" well. Can somebody tell me the reason?
char* cut_command_head(char *my_command, char *character) {
char command_arg[256];
//command_arg = (char *)calloc(256, sizeof(char));
char *special_position;
int len;
special_position = strstr(my_command, character);
//printf("special_position: %s\n", special_position);
for (int i=1; special_position[i] != '\0'; i++) {
//printf("spcial_position[%d]: %c\n", i, special_position[i]);
command_arg[i-1] = special_position[i];
//printf("command_arg[%d]: %c\n", i-1, command_arg[i-1]);
}
len = (int)strlen(command_arg);
//printf("command_arg len: %d\n", len);
command_arg[len] = '\0';
my_command = command_arg;
printf("my_command: %s\n", my_command);
return my_command;
}
int main(int argc, const char * argv[]) {
char *test = "cd xxx";
char *outcome;
outcome = cut_command_head(test, " ");
printf("outcome: %s\n",outcome);
return 0;
}
Upvotes: 2
Views: 121
Reputation: 70981
Here
my_command = command_arg;
you assign the address of a local variable to the variable you are returning. This local variable lives on the stack of cut_command_head()
.
This address is invalid after the function returned. Accessing the memory returned by cut_command_head()
provokes undefined behaviour.
You need to allocate memory somewhen, somewhere.
The easiest way is to use strdup()
(if available):
my_command = strdup(command_arg);
A portable approach is to use malloc()
followed by copying the data in question:
my_command = malloc(strlen(command_arg));
if (NULL != my_command)
{
strcpy(my_command, command_arg);
}
Also this looks strange:
len = (int)strlen(command_arg);
//printf("command_arg len: %d\n", len);
command_arg[len] = '\0';
Just remove it and initialise command_arg
to all zeros right at the beginning to makes sure it is always 0
-terminated:
char command_arg[256] = {0};
Upvotes: 5