I had an interview today for a possible internship with a company supplying IPTV solutions.
The interviewer asked a technical question, which I got with a little bit of help here and there but he said it was just as important to communicate how to solve the problem as well as actually implementing it. No idea whether I got the job, but we'll see.
The question he asked was write a C function to reverse a string. So I came up with something on a whiteboard which he seemed relatively happy with. I wanted to be sure I could always do it so I tested the code again at home, at which point I hit a weird issue (as I usually do when working with C, I might add).
Here's the code I wrote ('scuse the messiness of it, I was just hacking about):
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void strRev(char* originalString);
int main()
{
char* source;
source = "hello";
strRev(source);
return (0);
}
void strRev(char* originalString)
{
char* tempString = NULL;
int i = 0;
int j = 0;
int lengthOfTempString = 0;
int lengthOfOriginalString = 0;
lengthOfOriginalString = strlen(originalString);
tempString = malloc(sizeof(char) * lengthOfOriginalString);
lengthOfTempString = strlen(tempString);
printf("Length of tempString: %i\n",lengthOfTempString);
printf("Length of originalString: %i\n",lengthOfOriginalString);
printf("sizeof(char): %i\n",sizeof(char));
for (i = strlen(originalString); i >= 0; i--)
{
if (originalString == '\0')
{
printf("Null terminator detected\n");
}
else
{
tempString [j] = originalString;
j++;
}
}
*tempString+='\0';
printf("Original string: %s",originalString);
printf("\n");
printf("Newly reversed string: %s",tempString);
free(tempString);
}
Now, when I run this, I see something interesting. The strlen of originalString is 5, as it should be, and this is what the code reports.
So why is the strlen for tempString
9? That doesn't make any real sense to me, where's the 9 coming from? I know the size of a char* pointer is 4 bytes but that isn't important or relevant here from what I can see, even still there's no way that you could get 9 out of that. When it prints out tempString, I see the right output followed by 4 extra bytes of utter crap because the buffer is too big.
I'm now getting 9, which is an improvement on the even more random 16 and 24 I was getting earlier. Similarly, when I do:
tempString = malloc(sizeof(char));
without the additional sizeof as shown above, the length of tempString is apparently 16??
I really don't get what's going on here, I'm not exactly Brian Kernaghan when it comes to C but that just seems plain wrong. How does having a char*, then assigning it dynamically to a standard char produce 16? Shouldn't it be 1, or 4? I'm compiling using VS2005 if that helps, maybe something weird about the compiler?
This is actually bugging me, it doesn't seem right. Where did I go wrong?
TIA,
ukd.