memory alignment

A

aneesh

Hi All,
Im having a program
int main()
{
char* p = "hello";
printf("%d",*((int*)p));

}

char* is acutally non aligned and we r casting it to int* and
accessing the value, will there be any perfomance issue related to
alignment.
Thanks
Aneesh
 
J

Jens.Toerring

aneesh said:
Hi All,
Im having a program
int main()
{
char* p = "hello";
printf("%d",*((int*)p));

char* is acutally non aligned and we r casting it to int* and
accessing the value, will there be any perfomance issue related to
alignment.

There may not only be performance issues but, even worse, on archi-
tectures that require proper alignment you may get a bus error and
your program will get aborted. But you should ask this in a newsgroup
dedicated to the architecture you're using, standard C can't give you
any final answers on this.
Regards, Jens
--
_ _____ _____
| ||_ _||_ _| (e-mail address removed)-berlin.de
_ | | | | | |
| |_| | | | | | http://www.physik.fu-berlin.de/~toerring
\___/ens|_|homs|_|oerring
 
S

Simon Biber

You need:
#include said:
int main()
{
char* p = "hello";
printf("%d",*((int*)p));

Add:
return 0;
}

char* is acutally non aligned and we r casting it to int* and
accessing the value, will there be any perfomance issue related to
alignment.

Performance issues are the least of your worries. This is undefined
behaviour for good reasons.

a) If sizeof(int) > 6 then you are accessing out of the bounds of
the array.
b) If the object when interpreted as an integer forms a trap
representation your program may crash.
c) If the alignment is wrong for an integer, your program may crash
with a 'bus error' or equivalent.
 
M

Micah Cowan

Hi All,
Im having a program
int main()
{
char* p = "hello";
printf("%d",*((int*)p));

}

char* is acutally non aligned and we r casting it to int* and
accessing the value, will there be any perfomance issue related to
alignment.

Alignment problems lead to undefined behavior, which might be
simply lessened performance, or might be system-wide crash, or
might be to invoke nasal daemons. Aside from alignment, the mere
accessing of p through an lvalue of incompatible type, and the
lack of declaration for printf(), also invoke undefined behavior.

-Micah
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Members online

Forum statistics

Threads
473,755
Messages
2,569,537
Members
45,023
Latest member
websitedesig25

Latest Threads

Top