I have a c program I'm writing that I want to be portable and future compliant. The POSIX function strdup()
is not in the current C standard, but it has been added to the C2x standard. Will this code work properly with C standard compliant compilers in the future.
Will it work on both POSIX and non POSIX systems?
my_strdup.h
#ifndef MY_STRDUP_H
#define MY_STRDUP_H
#include <string.h>
#ifndef strdup
#ifdef _MSC_VER
#if _MSC_VER > 1920
#define strdup _strdup
#endif
#else
#define strdup mystrdup
#endif
#endif
char* mystrdup(const char* string_to_copy);
unsigned char* ucstrdup(const unsigned char* string_to_copy);
#endif // MY_STRDUP_H
my_strdup.c
#include "my_strdup.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char* mystrdup(const char* string_to_copy)
{
char* return_string = NULL;
size_t length = strlen(string_to_copy);
++length;
return_string = calloc(length, sizeof(*return_string));
if (return_string)
{
memcpy(return_string, string_to_copy, length - 1);
}
return return_string;
}
unsigned char* ucstrdup(const unsigned char* string_to_copy)
{
unsigned char* return_string = NULL;
size_t length = strlen((const char*)string_to_copy);
++length;
return_string = calloc(length, sizeof(*return_string));
if (return_string)
{
memcpy(return_string, string_to_copy, length - 1);
}
return return_string;
}
Post Answer Update:
This code is part of a project I am working on, the code that uses this code can be found in 4 questions on Code Review. Those questions are all related to unit tests I am writing for this project.
Here are the questions on code review in the order asked:
- Hand Coded State Driven Lexical Analyzer in C With Unit Test Part A
- Hand Coded State Driven Lexical Analyzer in C With Unit Test Part B
- Part C
- Follow up to Part C
Feel free to write answers for the questions as long as they follow the Code Review Guidelines