A Little Lost At Const And Casting


Micket

Member
Joined
Jul 16, 2006
Messages
196
Age
41
Location
Sweden, Gothenburg
Website
www.micket.com
Hello!
I've had some problems with libmodplug and i've found the bug that seems to be causing most problems with xm+many other formats.
Code:
#include <stdio.h>
 
int main() {
	const char foo[] = {0x12, 0x34,0X56};
	short bar = *((short*)(&foo[1]));
	printf("%X\n",bar);
}


This will write
3412
on my gp2x, and without const i get
5634

I find 3412 to be a rather strange result, as it's prior to the pointer.
What i'd like is the second result, even with const (i'd prefer not to hack at every other file at a bilion places to get libmodplug working)
( Compiled for my pc i get 5634 with and without const )

I.. well i simply dont know how to attack this problem at all, or why i ever get 3412 to start with.

I got some help on irc. Turns out i have to fix every unaligned read manually. Ack!
 
I'm not sure what const has to do with but I think the 3412 is to with alignment because I tried in on a Sun machine and that gives a bus error with and without the const which is a classic sign of an alignment problem.

What results do you get if you extend foo and try foo[2], foo[3], foo[4] and foo[5]?
 
The alignment is not guareenteed to be on and even boundary for foo[1] (or any element of foo) so accessing it as a short (16 bits) might fail (as Parkdyr go with the bus error on the sun). if you want to get a short at the pointer you will need to do it manually (assuming you want the next two byes to be in the short and you are on a little endian machine). Quick sample next:

Code:
#include <stdio.h>

int main() {
	short my_short; /// Compiler will make this an even address
	const char foo[] = {0x12, 0x34,0X56};

	short bar = 0;

	bar |= foo[1];			// put low order byte in
	bar |= (foo[2] << 8)); // put high order byte in
	printf("%X\n",bar);
}

The break out to two steps in not strictly needed but help sometimes visually. The zero before is needed because we are 'or'ing in the values. The compiler is guaranteed to align any type to the appropriate boundary for the language.

Note:: If the data is stored big endian then just reverse the subscripts of foo in the two lines.
 
Thanks for the replies.
I've sort of solved it (wrote a #define for reading the shorts (as well as ints) ) and actually got fasttracker songs to work.
Still a few bugs but i'll hopefully sort it out tonight!
 
Back
Top