I have come across this before, and the answer has been either to null-terminate the string, or to be sure to allocate enough memory for the string. Here is the relevant snippet of code:
for (z; z<mountable_volumes; z++)
{
main_items[z] = malloc(strlen(volumes[z])+2);
main_items[z] = volumes[z];
printf("main_items[%i]: %s\n", z, volumes[z]);
}
main_items[z] = NULL;
return main_items;
Volumes[] is correct, but when its contents get created into main_items[], it goes bad. I have tried playing with malloc, even outright allocating way more ram than necessary. I have also tried tacking on a '\0' to the end of each main_items[] element. I have tried using strcpy, strncpy, sprintf with the same results.
Here is the log from my program:
volumes[0]: Unmount /sdcard
volumes[1]: Mount /system
volumes[2]: Unmount /cache
volumes[3]: Mount /data
volumes[0]: Unmount /sdc)☻
main_items[1]: Mount /syste)☻
main_items[2]: Unmount /cac‼
main_items[3]: Mount /data
What am I missing? Thanks! I can paste more of the function if its needed.
EDIT:
here is the entire function: (I have applied the strndup() and free() tips)
char** get_mount_menu_options()
{
Volume * device_volumes = get_device_volumes();
num_volumes = get_num_volumes();
char** volumes = malloc (num_volumes * sizeof (char *));
int mountable_volumes = 0;
int usb_storage_enabled = is_usb_storage_enabled();
int i;
for (i=0; i<num_volumes; i++)
{
volumes[i] = "";
Volume *v = &device_volumes[i];
char* operation;
if (is_path_mountable(v->mount_point) != -1)
{
if (is_path_mounted(v->mount_point)) operation = "Unmount";
else operation = "Mount";
volumes[mountable_volumes] = malloc(sizeof(char*));
printf("volumes[%i]: %s %s\n", mountable_volumes, operation, v->mount_point);
sprintf(volumes[mountable_volumes], "%s %s", operation, v->mount_point);
mountable_volumes++;
}
}
char **main_items = malloc (num_volumes * sizeof (char *));
int z;
for (z=0; z<mountable_volumes; z++)
{
main_items[z] = strndup(volumes[z], strlen(volumes[z]));
free(volumes[z]);
printf("main_items[%i]: %s\n", z, volumes[z]);
}
main_items[z] = NULL;
return main_items;
}
CURRENT LOG:
volumes[0]: Unmount /sdcard
volumes[1]: Mount /system
volumes[2]: Unmount /cache
volumes[3]: Mount /data
main_items[0]: Unmount /sdc)☻
main_items[1]: Mount /syste)☻
main_items[2]: Unmount ¿♠
main_items[3]:
Thanks everyone!
main_items?main_items[z] = volumes[z];seems incorrect, you should be usingstrncpy. Arrays cannot be assigned.