Can strncpy return 0?

The man page strncpystates:

char * strncpy (char * dest, const char * src, size_t n);

The strcpy () and strncpy () functions return a pointer to the destination string dest.

Is it possible that strncpy(buff, "something", 9) == 0will be true if char buff[100]?

UPDATE

I also find this not very likely, but it is part of the program that I have to do for bufferoverflow, and this condition remains in my way to achieve this.

+4
source share
6 answers

No .

Judging by the facts that

dest == NULL,
.

+5

. ? , dest. , dest NULL, NULL.

buff NULL ( , char buff[100]), , , NULL.

, .

+4

strcpy() strncpy() dest.

, dest. NULL, , dest NULL, NULL ( ) , , undefined . Btw. , , :

undefined, dest, src .

, , NULL.

+2

, undefined, NULL.

, NULL, - NULL. ( ) segfault, 0.

:

strncpy(buff, "something", 9)

NULL ( char buff[100]), 0, 9.

+2

ISO/IEC 9899: 2011 §7.24.2.4/c4 strncpy: function

1   #include <string.h>
    char *strncpy(char * restrict s1,
    const char * restrict s2,
    size_t n);

2 strncpy n (, > , ) , s2, ,

3 , s2, - , , n , > , s1, n .

4 strncpy s1. s1. , undefined.

, strncpy 0 (.. NULL) undefined, s1 NULL n .

LIVE DEMO

+1

Yes, it strncpy()can come back NULL. Just a mmaprecordable page with the address zero in the system, which defines it NULLas a pointer with zero as its numerical value:

#include <sys/mman.h>
#include <stdio.h>
#include <strings.h>

int main( int argc, char **argv )
{
    char *p;
    char *buf = mmap( ( void * ) 0, 4096,
        PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_FIXED | MAP_ANON, -1, 0 );
    p = strncpy( buf, "string", strlen( "string" ) );
    printf( "p: %p\n", p );
    printf( "NULL: %p\n", NULL );
    return( 0 );
}

Yes, this intentionally violates the standard C requirement, which NULLshould not point to a valid object, therefore this behavior is undefined.

But this is CAN .

0
source

Source: https://habr.com/ru/post/1614877/


All Articles