-1

I am trying to tokenize the user inputed commands for a shell program. The program runs but I don't think that it is filling the param array I have declared. I'm sorry if it seems that I don't have a ton of information as I am learning this as a do it, but I am not sure why it isn't filling param. Any help would be grateful and if you need any additional information please feel free to ask.

#include "HeaderFile.h"
#include <stdio.h>
#include <stdlib.h>
#define token_delimiter " \n\r"

char **shell_read(char *line, char **param){

   line = NULL;
   ssize_t size = 0;
   getline(&line, &size, stdin);
   //printf("%s", line);
   int i = 0;
   char *line_token;
   line_token = strtok(line, token_delimiter);
   printf("%s", line_token);
   for(i=1; line_token!=NULL; i++){
       param[i] = line_token;
       line_token = strtok(NULL, token_delimiter);

   }
   param[0] = NULL;
   return(param);
}
Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97
  • How are you allocating `param`? Oh, and don't write `return(param)`, `return` is not a funtion. You also have a memory leak, you need to `free()` `line`. – Iharob Al Asimi Sep 20 '16 at 22:27
  • just added the following to allocate 'param', using _param = malloc(buffer * sizeof(char *));_ where _buffer = 64;_ . also fixed the return issue and the memory leak – Chris Masterson Sep 20 '16 at 22:33
  • The `return` thing was ok, it's not an issue. But it just looks ugly. – Iharob Al Asimi Sep 20 '16 at 22:35
  • 1
    You can't *"fix"* the memory leak because all of your pointers point to that memory. And there's not enough information in the question to know where the problems are. See [minimal, complete, and verifiable example](https://stackoverflow.com/help/mcve). – user3386109 Sep 20 '16 at 22:36

1 Answers1

-1

something like this:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define token_delimiter " \n\r"

char **shell_read(void){//Parameters are not necessary. because they are made in this function.
    char *line = NULL;
    size_t size = 0;
    ssize_t len;
    if(-1 == (len = getline(&line, &size, stdin))){
        free(line);
        return NULL;
    }

    char **param = malloc(sizeof(*param) * ((len + 1)/2 + 1));//last +1 for NULL
    int i = 0;
    char *line_token = strtok(line, token_delimiter);

    while(line_token != NULL){
        param[i++] = strdup(line_token);//need allocate and copy
        line_token = strtok(NULL, token_delimiter);
    }
    param[i] = NULL;
    free(line);

    return param;
}

int main(void){
    putchar('>');fflush(stdout);

    char **tokens = shell_read();
    if(tokens){
        for(char **token = tokens; *token; ++token){
            puts(*token);
            free(*token);
        }
        free(tokens);
    }
    return 0;
}
BLUEPIXY
  • 39,699
  • 7
  • 33
  • 70