So, I have to write a program that among other things, parses a string and breaks it up.
So if I have the input "ps -aux" I need to store this in an output array where output = "ps", output = "-aux" and output = NULL.
The program is supposed to run smoothly on Linux, which it does...but, for some reason doesn't run properly at all on windows. This wouldn't be much of an issue, except for the fact that I'm only using standard library functions to achieve this goal at the moment, so I fear something may be wonky in my code and I"m just not picking up on it...
The way I've approached it is like thus:
a) read in a string
b) break it up into the 'parameters/program name'
c) (testing) print out the program name
Part (b) is accomplished by first stripping off any leading or trailing whitespace that could possibly be input. Then we find the first string, using ' ' as a delimiter. Continue this process until we've exhausted the original input and have now broken it up into several different strings.
What's the problem exactly? Well, windows keeps printing "ps4" or something similarly wacky (like -aux4...junk chars...) when I try to print any other things in the array (well, double pointer, but I'm using array syntax to index it). Linux does JUST fine and everything is nice and good.
But why the hell is windows randomly adding a new character(s) to my strings? I can't ANYWHERE find where it's getting these extra chars. I'll check the string before I call strncpy() and it seems all fine and what have you, but then I call the function and suddenly the string is not only longer than what I wanted it to be, but it also has extra chars! Is this a programming error on my behalf, or is it windows just being windows?
Here is the main function:
The getparams(const char *input) function:
char *ptr = " ps -aux ";
char **test = getparams(ptr);
And the two utility functions strfind and strtrim...
char *tmp = (char *)input;
size_t counter = 1;
tmp = strtrim(tmp);
output = malloc(strlen(tmp)*sizeof(char *)); // num(params+prgname) <= strlen(input)
output = strfind(tmp, ' ');
for(i = strlen(output); tmp[i] != '\0'; )
output[counter] = strfind(tmp+i, ' ');
i += strlen(output[counter]);
output = realloc(output, (counter+1) * sizeof(char *));
output[counter] = NULL;
strfind(const char *src, char c):
strtrim(const char *src):
char cur = *src;
char *dst, *tmp = (char *)src;
for(size = 1; tmp[size] != '\0' && tmp[size] != c; size++) cur = tmp[size];
dst = malloc(size+1);
strncpy(dst, src, size);
int i = 0;
size_t diff = 0, len = strlen(src);
char *start, *s;
// count leading whitespace
start = src+i; // the bit we're interested in starts at src+i
i = len-1; // back end starts at src[len-1]
// count trailing whitespace
s = malloc(len-diff+1); // bytes required = old length - whitespace chars + '\0'
strncpy(s, start, len-diff); // copy nonwhitespace chars into a new string