Google Interview Question
Software Engineer / Developersis it really asked by google ..might they r looking for all possible test cases covered
here is the code let me know if i missed anything
/*#include<stdio.h>
#include<string.h>
#include<stdlib.h>
void xstrncpy(const char* src,char * tar,int n);
int main()
{
char source[]="shashank";
char *target=(char *)malloc(strlen(source)+1);
xstrncpy(source,target,5);
printf("Our target is : %s",target);
return 0;
}
void xstrncpy(const char* src,char * tar, int n)
{ int i=0;
if(n>(signed)strlen(src))
return;
while(*src && i<n)
{
*tar=*src;
src++;
tar++;
i++;
}
*tar='\0';
}*/
char* strncpy (char* dst_str, const char* src_str, int length)
{
if (src_str)
{
int i = 0;
int src_length = strlen(src_str);
int n = (length < src_length)? length : src_length;
for (i = 0; i < n; i++)
{
dst_str[i] = src_str[i];
}
if (n < length)
{ //fill with the null char until length
for (i = n; i < length; i++)
dst_str[i] = '\0';
}
}
}
Really is this Google's question? Its a job of caller to allocate sufficient memory before calling this function. Function silently truncates additional characters.
char* strncopy(char *dest, const char *src, int n)
{
int i = 0;
for(i = 0; i < n-1 && src[i]!='\0'; i++)
dest[i] = src[i];
dest[i] = '\0';
return dest;
}
we can't calculate the strlen(dest), due to buffer overlfow we do use strncpy instead of stcpy. how u'll calculate the strlen of newly allocated buffer?
- Krish May 20, 2011