Below is a pared-down (error/null checks omitted) snippet of C/Obj-C code that uses sysctl to get the argv of a particular process with PID 50.
...
int getProcessArgs[3] = { CTL_KERN, KERN_PROCARGS, 50 };
sysctl(getProcessArgs, 3, NULL, &length, NULL, 0);
char* processArgs = malloc(length * sizeof(char));
sysctl(getProcessArgs, 3, processArgs, &length, NULL, 0);
...
The first call to sysctl (to determine the size of the argv string array) succeeds. The returned length is ~1600, larger than I would expect, but I suppose not unreasonable. Malloc succeeds. The second call to sysctl returns -1, setting errno to 22, E_INVAL.
I've looked at other code, including that from this question, but can't see the problem with mine. What am I missing?