Interview Question






Comment hidden because of low score. Click to expand.
0
of 0 vote

I think the question is wrong in more than one way:
- The subject of the cast should be void*, not void
- But even more importantly, the cast should happen from void* to (short*) not the other way around. There is no memory alignment issue with casting to void*

The alignment issue is such that every short is of 2 bytes size. Most modern processors work with word sizes that are multiple of 2, varying anywhere between 4 bytes, up to 32 bytes. Assume you have a processor that fetches 2 bytes of data from memory (old processor that is). It is guaranteed that anything it fetches will have a starting address that is even. Now take the following program snippet:

char *c = (char*)malloc(100 * sizeof(char));
   for (i = 0; i < 99; ++i) {
      short s = *((short*)c);
      printf("%hd", s);
      ++c;
   }

So, I am allocating 100 bytes, and accessing 99 shorts from it, by moving my pointer one byte at a time. So, the short will start from odd address then even address then odd ...

Depending on what compiler/OS/processor you use, this at the best (worst?) case it will be slow. In the worst (best?) will crash. The crash is simple: Anything accessing 2 bytes, must start at an even address. So this will be an alignment exception.

The slowness is caused by sometimes needing to access memory twice for each print. When you are accessing the short at address 0, it is easy, the processor fetches bytes 0 and 1, and prints the short. When you are accessing the short that starts at address 1, however, since it cant access bytes 1 and 2 in one shot, it accesses bytes 0, 1, throws away 0, keeps 1. Then accesses bytes 2,3, throws away byte-3, keeps byte-2. Then makes the needed short by combining byte 1 and byte 2.

You see it took much longer than simply reading two bytes in one shot and filling the register from it.

- Anonymous December 25, 2010 | Flag Reply


Add a Comment
Name:

Writing Code? Surround your code with {{{ and }}} to preserve whitespace.

Books

is a comprehensive book on getting a job at a top tech company, while focuses on dev interviews and does this for PMs.

Learn More

Videos

CareerCup's interview videos give you a real-life look at technical interviews. In these unscripted videos, watch how other candidates handle tough questions and how the interviewer thinks about their performance.

Learn More

Resume Review

Most engineers make critical mistakes on their resumes -- we can fix your resume with our custom resume review service. And, we use fellow engineers as our resume reviewers, so you can be sure that we "get" what you're saying.

Learn More

Mock Interviews

Our Mock Interviews will be conducted "in character" just like a real interview, and can focus on whatever topics you want. All our interviewers have worked for Microsoft, Google or Amazon, you know you'll get a true-to-life experience.

Learn More