While loop doing strage thing with variables

Question about which tools to use, bugs, the best way to implement a function, etc should go here. Don't forget to see if your question is answered in the wiki first! When in doubt post here.
Post Reply
madpickle
Posts: 3
Joined: Thu Dec 01, 2022 5:48 pm
Libera.chat IRC: madpickle
Location: The Milky Way Galaxy
Contact:

While loop doing strage thing with variables

Post 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. :)
Proud user of GCC.
Octocontrabass
Member
Member
Posts: 5562
Joined: Mon Mar 25, 2013 7:01 pm

Re: While loop doing strage thing with variables

Post 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.
MichaelPetch
Member
Member
Posts: 797
Joined: Fri Aug 26, 2016 1:41 pm
Libera.chat IRC: mpetch

Re: While loop doing strage thing with variables

Post 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.
Post Reply