Sunday, October 29, 2006

While at the interview was asked about the posibility to read Integer that is misaligned in the memory. Argued with the guru that you can but he was sure I can not. Here is a proof that I am right:

// pointers_game.cpp - proff that one can read integer from miss aligned memory adress at least at 80x86
// achitecture
#include
int main(int argc, char* argv[])
{
char * p = new char[100];
for (int i =0; i < 100; i++)
{
p[i] = 'A';
}
p[99] = '\0';
printf("the original pointer = %d\n",(unsigned int) p);
void * a = (void *) p;
a = (void *)(((unsigned int)a) + 1);
printf("the incremented pointer = %d\n",(unsigned int) a);
int b = *((int *)a) ;
printf("the integer that read by pointer = %X\n",(unsigned int) b);
printf("%s",p);
printf("\nHello World!\n");
delete (p);
return 0;
}

No comments:

Followers