SuperKael
SuperKael

Reputation: 226

Strange behavior with string literals in C kernel

I am relatively new to C, I admit, but I thought I understood the concepts pretty well. Despite this, I am noticing some odd behavior with string literals, that my google searching seems to indicate it shouldn't be happening. Is there something important I am missing, or is this an indication of some underlying problem in my kernel? When running this code:

debug_print("Directly in parameter.");

char test1[] = "With array.";
debug_print(test1);

char* test2 = "With pointer.";
debug_print(test2);

char test3[] = "With array, then pointer.";
char* test3_1 = &test3[0];
debug_print(test3_1);

char* test4 = "With pointer, then malloc.";
char* test4_1 = malloc(27);
memory_copy(test4, test4_1, 27);
debug_print(test4_1);

char test5[] = "With array, then malloc.";
char* test5_1 = malloc(25);
memory_copy(test5, test5_1, 25);
debug_print(test5_1);

(debug_print takes a const char* as a parameter, and prints it to serial0. memory_copy copies memory from the first parameter to the second, of the length specified in the third parameter. The malloc function is also custom, but I have done extensive testing to ensure it works fine.)

I get this output:

                               <-- There is a null string here...
With array.
                               <-- There is a null string here...
With array, then pointer.
                               <-- There is a null string here...
With array, then malloc.

It would seem that the string literal is apparently ignored if it is not initially stored as a char array. Why could this be? In case it is helpful, I am compiling with gcc with these args:

-ffreestanding -g -std=c99 -m32 -masm=intel -Wall

EDIT: As requested, here is my debug_print code:

void debug_print(const char* message) {
    for (int i = 0;message[i] != 0;i++) port_byte_out(0x3F8, message[i]);
    port_byte_out(0x3F8, '\r');
    port_byte_out(0x3F8, '\n');
}

and for good measure, here's memory_copy, since I didn't realize it was similar to a standard c function.

void memory_copy(const char* source, char* dest, int no_bytes) {
    int i;
    for (i = 0; i < no_bytes; i++) {
        *(dest + i) = *(source + i);
    }
}

Upvotes: 3

Views: 153

Answers (1)

SuperKael
SuperKael

Reputation: 226

Well I'm dumb - Thanks to @Matthias for suggesting using objdump. Upon doing so, I realized that the string literals were in a different section than the rest of my code. More specifically, my code is in '.text' while the literals were somewhere else, not sure where exactly. As part of my Makefile, I was doing:

objcopy -O binary -j .text $< $@

Notice the '-j .text'. I'm not sure why I was doing that exactly, it was trashing the literals! Thanks, and I apologize for my idiocy.

Upvotes: 2

Related Questions