S
Stefan Ram
I have written a function to copy a substring:
char * salsub( char const * const s, char const * const p )
{ ptrdiff_t const l = p - s;
char * const m = malloc(( size_t )( l + 1 ));
if( m ){ strncpy( m, s,( size_t )l ); m[ l ]= 0; }
return m; }
Now, AFAIK, ISO-C does not guarantee that a difference
of pointers can be represented by a value of the type
"ptrdiff_t". I would like my function to return 0
(not allocating anything) if this is the case for the
difference between p and s here. How could I detect
this case?
Then, possibly PTRDIFF_MAX might be larger than
SIZE_MAX, so the cast ( size_t )( l + 1 ) or
( size_t )l might have the "wrong" value. I also would
like the function to return 0 and not to allocate
anything in this case. How could this be done?
Possibly casting to size_t and then back to ptrdiff_t,
to see if it still has the same value?
char * salsub( char const * const s, char const * const p )
{ ptrdiff_t const l = p - s;
char * const m = malloc(( size_t )( l + 1 ));
if( m ){ strncpy( m, s,( size_t )l ); m[ l ]= 0; }
return m; }
Now, AFAIK, ISO-C does not guarantee that a difference
of pointers can be represented by a value of the type
"ptrdiff_t". I would like my function to return 0
(not allocating anything) if this is the case for the
difference between p and s here. How could I detect
this case?
Then, possibly PTRDIFF_MAX might be larger than
SIZE_MAX, so the cast ( size_t )( l + 1 ) or
( size_t )l might have the "wrong" value. I also would
like the function to return 0 and not to allocate
anything in this case. How could this be done?
Possibly casting to size_t and then back to ptrdiff_t,
to see if it still has the same value?