user6274708
user6274708

Reputation:

Safe functions in visual studio 2015

While coding C under windows,visual studio 2015,I found my self forced to amend my code due to the deprecated functions,by adding a second parameter,and of course using a safe function(e.g. ending with _s).

I was wondering,do these functions exist in the C standard library,and will i be able to compile them with a C compiler if I transfer them to my linux partition?

My concern arose when i was writing a string flip about an offset function:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char *flipstr(char *str, size_t size, size_t offset);

int main(int , char **)
{
    char str[] = "JonSon";
    char *p = flipstr(str, sizeof(str), 3);
    if (p) {
        printf("%s\n", p);
    }
    return 0;
}

char *flipstr(char *str, size_t size, size_t offset)
{
    if (offset > strlen(str)) {
        return NULL;
    }

    char *tmp = (char *)calloc(size, sizeof(char));

    strncpy_s(tmp, size, str, offset);

    memmove(str, str + offset, strlen(str + offset));

    memcpy(str + strlen(str + offset), tmp, strlen(tmp));

    free(tmp);

    return str;
}

Upvotes: 2

Views: 1072

Answers (2)

Lundin
Lundin

Reputation: 214310

There are several issues here...

First of all, there is nothing wrong with using strcpy, that's a myth. And it is not deprecated, that's just Microsoft gaga.

Second, strncpy was never intended to be a safe version of strcpy. It was never intended to be used for anything but an old, non-standard string format in ancient Unix.

Third, strncpy is unsafe and dangerous. See this and this. Plenty of blogs about this to be found.

So forget about strncpy, and consequently, also forget about strncpy_s. There is actually a function called strncpy_s in the C11 bounds-checking interface (which isn't mandatory for compilers to implement).

If this C11 standard function is fully compatible with non-standard Microsoft junk functions with the same name, I have no idea. I wouldn't count on it. But since Visual Studio 2015 is an ancient compiler from the early 90s, C11 is not something you can use anyhow.

Upvotes: 0

Yakov Galka
Yakov Galka

Reputation: 72519

No, most of them aren't standard and you shouldn't use them just because somebody in Microsoft decided to "deprecate" half the standard library in favor of their non-standard extensions. Sure, there is some justification of what they did, but in the end it's simply ridiculous. You are better to disable the warnings and write a portable C/C++.

Upvotes: 6

Related Questions