Page 1 of 1

While loop doing strage thing with variables

Posted: Sat Dec 03, 2022 9:18 pm
by madpickle
Ok... So I'm trying to make a simple print function for my OS.
But inside my while loop the iterator seems to get reset every iteration of the loop. Here's my code.

Code: Select all

extern void main() {

	uint8_t i = 0; // declare i
	
	void setchar(uint16_t id, char letter) {
		volatile char *addr = (char*)0xB8000 + id * 2;
		*addr = letter;
		return;
	}

	void print(char string[]) {
		i = 0; // set i to 0
		while (string[i] != '\0') {
			// i is 0 after EVERY iteration (not just first time)
			setchar(i, string[i]);
			i = i + 1;
			// i does get set to 1 here but is reset to 0 on next iteration
		}
		return;
	}

	print("test");
	return;
}
It just prints the first letter of the string "t".
And my setchar function works just fine.
If set all the characters manually...

Code: Select all

setchar(0, 't');
setchar(1, 'e');
setchar(2, 's');
setchar(3, 't');
It works like a charm and prints "test", as you would expect.

I don't know why this is doing that. It may just be a super simple beginner mistake, but I don't know. Any help would be appreciated, Thanks. :)

Re: While loop doing strage thing with variables

Posted: Sun Dec 04, 2022 11:51 pm
by Octocontrabass
Usually this indicates a problem with your environment rather than the code itself. For example, maybe your stack isn't set up correctly, or you're passing the wrong options to your cross-compiler, or you're not using a cross-compiler when you should be.

Using a debugger to examine the instructions being executed should help you spot the problem.

Re: While loop doing strage thing with variables

Posted: Mon Dec 05, 2022 10:46 pm
by MichaelPetch
Or you didn't load enough of your kernel into memory and the string was stored statically in a section that didn't get loaded. You may have also somehow excluded the section with the string from the executable. Octo is correct that the problem likely exists outside the code you are showing. If you had a project on Github or other similar service it might be easier to identify.