I'm trying to run a shell script using posix_spawn, by trying to convert from NSArray to char array with a NULL in the last element, I end up crashing my system. Below is the original code that has no error.
NSArray *arg_array = nil;
arg_array = @[@"/bin/bash", @"/var/somefile.sh"];
char **argv = NULL;
NSInteger numargv = arg_array.count;
if (numargv) {
argv = (char **)calloc(numargv, sizeof(char*)) ;
if (argv) {
for (NSInteger i=0;i<numargv;i++) {
NSString *nsString = arg_array[i];
if (i==0){
NSArray* spliteArray = [nsString componentsSeparatedByString: @"/"];
NSString* cStringFirstArgv = [spliteArray lastObject];
nsString = cStringFirstArgv;
}
char *cString = (char *)malloc([nsString lengthOfBytesUsingEncoding:NSUTF8StringEncoding] + 1); // + 1 for \0
if (cString) {
strcpy(cString, nsString.UTF8String);
argv[i] = cString;
} else {
// error
}
}
}
}
pid_t pid;
int status;
//const char *argv[] = {"bash", "/var/test.sh", NULL}; This is what I expected argv to be, a NULL in the last element
posix_spawnp(&pid, "bash", NULL, NULL, (char* const*)argv, NULL);
waitpid(pid, &status, WEXITED);
argv currently is {"bash", "/var/test.sh"}, however I trying to make it to an array like this:{"bash", "/var/test.sh", NULL} so that I could run posix_spawn successfully. Any idea how to fix this? Thanks in advance!
calloc(numargv + 1in the first place.cStringWithEncoding: