0

I am writing a kernel in c. I am trying to write a split string function that takes in a string (char s[]), a delimiter (char d), and a pointer to a 2 dimensional output array (char** outp) that returns the length of items written to outp. For reference, I terminated all strings with '\n'. The problem occurs when I try to read from outp after calling split, it returns unexpected values. However, when I read outp inside the split function, the split string array value is correct.

For demo purposes, i am going to split "The quick brown fox jumps over the lazy dog" with a space character.

EDIT: I tried allocating memory for it.

Here's the output from inside the split function

The
quick
brown
fox
jumped
over
the
lazy
dog

Here's the output from printing outp after calling split.

9
lazy
the
the
quick
the
the
brown
the

Edit: Here's the memory allocator function

u32 free_mem_addr = 0x10000;
u32 kmalloc(u32 size, int align, u32 *phys_addr) {
    /* Pages are aligned to 4K, or 0x1000 */
    if (align == 1 && (free_mem_addr & 0xFFFFF000)) {
        free_mem_addr &= 0xFFFFF000;
        free_mem_addr += 0x1000;
    }
    /* Save also the physical address */
    if (phys_addr) *phys_addr = free_mem_addr;

    u32 ret = free_mem_addr;
    free_mem_addr += size; /* Remember to increment the pointer */
    return ret;
}

Edit: Here's where I allocated the memory
```c
output = (char**)kmalloc(MAX_ARG_COUNT * MAX_ARG_SIZE, 1, (u32*)&output);
Here's the input handler in the kernel.
```c
void handle_input(char* input) 
{
    char** output;
    int arg_len = split(input, ' ', output);
    kprint("\n");
    char str[5];
    int_to_ascii(arg_len, str);
    kprint(str);
    int i;
    for (i = 0; i < arg_len; i++)
    {
        kprint(output[i])
    }
    kprint("\n$> ");
}

Here's the split string function

int split(char s[], char d, char** outp)
{
    int i;
    int size = 0;
    int buffer_size = 0;

    for (i = 0; i < strlen(s); i++)
    {
        if (s[i] == d)
        {
            outp[size][buffer_size] = '\0';
            kprint(outp[size]);
            kprint("\n");
            size++;
            buffer_size = 0;
        }
        else
        {
            outp[size][buffer_size] = s[i];
            buffer_size++;
        }
    }
    kprint(outp[size]);
    return size+1;
}
mike
  • 100
  • 7
  • 2
    `output` is uninitialized. You'll have to allocate some memory and assign `output` to point to it. – Fred Larson Jun 19 '20 at 20:24
  • 1
    Does this answer your question? [What happens to a declared, uninitialized variable in C? Does it have a value?](https://stackoverflow.com/questions/1597405/what-happens-to-a-declared-uninitialized-variable-in-c-does-it-have-a-value) – Fred Larson Jun 19 '20 at 20:26

0 Answers0