Amazon Interview Question
Software Engineer / DevelopersI am concerned here about the operation strcat.
P is a character pointer, and using malloc it got a space for 25 characters.
Similar is the case with Q.
Both have some values copied in their memory locations.
So, for P, value will be like amazon_ _ _ _ _ _ _25thlocation
For Q, value will be like hyd_ _ _ _ _ _25thlocation.
When we concat them, will the empty spaces in P and Q be trimmed off or not?
all is fine but one can say a missing free mmory part but i think that should be not a big issue here
As such, nothing is wrong with the program, unless you want to implement coding best-practices:
1. You should check return of malloc - whether it has returned NULL or not.
2. Use strncpy, and strncat; Although this is not be an absolute requirement as long as malloc size and strings are hard-coded.
3. main should return int, and should also return an exit value.
4. p and q should be initialized to NULL.
Printf uses character pointer and prints it until it finds a null character. As malloc returns a memory with garbage data printf may print some garbage data after two strings 'amazon' and 'hyd'.so we need to either initialise the memory allocated with malloc to null or allocate the memory using calloc.
The issue seems to be the fact that strcpy() and strcat() do not check how much memory is actually allocated to the addresses (similar to C doing no bound checking on array). For example, even if one does this, it still appears to work:
char *p = (char *) malloc (0);
char *q = (char *) malloc (0);
Check for the NULL after every malloc and free the memory at the end of the program (though its not required in this case but its generally a good practice to do that).
- mja August 04, 2011