My task is like this: I need to implement the strcpy
function under the following constraints:
- The function can have no more than seven statements.
- It should be as fast as possible.
- It should use the minimum amount of memory it can.
- In the function that will call my
strcpy
, the destination address will be held as follows:char* newDestination = NULL;
- The prototype of the
strcpy
function should be:void myStrcp(void** dst, void* src);
I came out with this solution which uses uint64_t
to copy each iteration eight bytes. If so, my questions would be:
- Is there a better solution than mine - and if so please explain why it is better?
- Does it matter on which OS we are running the program (
Windows
Vs.Linux
) and / or platform?
My solution (On Windows):
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <conio.h>
void strCpy(void **dst, void *src);
int main()
{
char *newLocation = NULL;
strCpy((void **)&newLocation, "stringToBeCopied");
printf("after my strcpy dst has the string: %s \n", newLocation);
free(newLocation);
getch();
return 0;
}
void strCpy(void** dst, void* src)
{
// Allocating memory for the dst string
uint64_t i, length = strlen((char *)src), *locDst =
(uint64_t *) malloc(length + 1), *locSrc = (uint64_t *) src;
*dst = locDst;
// Copy 8 Bytes each iteration
for (i = 0; i < length / 8; *locDst++ = *locSrc++, ++i);
// In case the length of the string is not alligned to 8 Bytes - copy the remainder
// (last iteration)
char *char_dst = (char *)locDst, *char_src = (char *)locSrc;
for (; *char_src != '\0'; *char_dst++ = *char_src++);
// NULL terminator
*char_dst = '\0';
}