0

I can't be the only one who begins to feel overwhelmed by all the asterisks... I'm sorry if you find this question redundant but I am really having trouble applying the pointer concepts I've already read about to this particular instance. I'm trying to figure out why it is that I get a core dump every time I run this bit of code:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>


void parseInput(char *input, char **argv){

    printf("%s",input);

    int count=0;
    char delimit[] = " \t\n\r";
    char* token;

    /* get the first token */
    token = strtok(input, delimit);
    argv[count] = &token;

    count++;

    while( argv[count]!= NULL ) {
            printf("%s\n", *argv[count]);
            token = strtok(NULL, delimit);
            argv[count] = &token;

            count++;
    }

}

main(){

int bytes_read;
int bytes = 100;
char *input, c;

char prompt[] = "% ";
int length, j;

do{
    printf("%s",prompt);
    input = (char *)malloc(bytes);
    bytes_read = getline(&input, &bytes, stdin);
    length = sizeof(input)/sizeof(input[0]);

    char *argv[length];

    parseInput(input, argv);

    free(input);

}while(bytes_read != -1);

return 0;
}

What I want to do is take the input array, tokenize it, and then set each element of argv[] to point to the beginning of each token. I think my troubles are with really not knowing how to reference the arrays in a manner suitable to this purpose. What can I do to remedy this?

Thanks.

mkhbragg
  • 131
  • 3
  • 12

1 Answers1

1

You're stepping off the end of argv[]. It's not NULL-terminated. Remove the NULL check and only consume /argc/ arguments from argv.

I also recommend you use 'valgrind' for problems like this - it's very helpful. In this case the output says:

==4933== Conditional jump or move depends on uninitialised value(s)
==4933==    at 0x4E96BB0: getdelim (iogetdelim.c:101)
==4933==    by 0x400792: main (test.c:44)
==4933==

and you can trace right back to your line 44, where you do the argv[] fencepost.

Also, depending on your system, assigning to argv memory might be a totaly bogus move. Use the dynamic (heap alloc) or stack (local or heap alloc) instead.

BadZen
  • 4,083
  • 2
  • 25
  • 48