2

I am working on creating a shell similar to bash. I am running into an error when attempting to get the arguments associated with a command (ie. ls -l). I've searched online and haven't found anything useful.

char *userInCopy;
char *ret;
userInCopy = (char*)calloc(1024, sizeof(char));
ret = (char*)calloc(64, sizeof(char));
strcpy(userInCopy, userIn);
int i = 0;
while((ret = strsep(&userInCopy, " "))){
    *(args + i) = (char*)calloc(strlen(ret), sizeof(char));
    strcpy((*(args+i)), ret);
    i++;
    ret = (char*) realloc(ret, (64)* sizeof(char));
} 

I get input from the user in the char userIn and that is allocated properly. I then parse through the input using strsep getting each argument individually. I can get the ls argument and -l argument but then when it goes to realloc after the -l it gives me the "realloc(): invalid pointer" error. Im lost at why this would work the first time after getting the ls argument but fails after getting the -l argument. Any suggestions?

epartridge
  • 31
  • 3
  • 4
    The size you give [`realloc`](https://en.cppreference.com/w/c/memory/realloc) is the new *total* size. It's not how much extra it should add. Also note that you should never assign back to the pointer you pass in, as `realloc` can fail and return `NULL`, in which case you lose the original pointer. Lastly, in C you [should not cast the result of `malloc`, `calloc` or `realloc`](https://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc/). – Some programmer dude Feb 28 '19 at 09:03
  • 1
    On an unrelated note, the `strsep` function is a POSIX standard function, not a C standard function. Just so you know if you want to use it on other platforms. – Some programmer dude Feb 28 '19 at 09:05
  • 2
    Stylistic point: Don't use `*(args + i)`. Instead, use the equivalent, but much clearer, `args[i]`. – Tom Karzes Feb 28 '19 at 09:08

1 Answers1

5

The problem is you are overwriting the ret with strsep return value.

while((ret = strsep(&userInCopy, " "))) //Here

Have a another temporary variable to store strsep return.


From the realloc man page.

void *realloc(void *ptr, size_t size);

ptr must have been returned by an earlier call to malloc(), calloc() or realloc().

kiran Biradar
  • 12,700
  • 3
  • 19
  • 44