D
DSF
Hello,
Is a pointer harmless as long as it's not dereferenced, or fed to a
function that dereferences it? After all, a pointer is just a number
until you try to access where it points to (at?) It would seem
logical that the answer to this is yes, but C can sometimes appear to
be "highly illogical," so I thought I'd ask here.
The reason I ask is that I'm creating a few string functions for my
personal library and I noticed that two of the pointers in the
following code may point to well beyond the string 'str' if 'pos' or
'n' are out of range.
/* deletes n chars from string str starting at position pos */
/* if pos > length of str, returns error */
/* if pos + n > length of str, deletes from pos to end of str */
int strdel(char *str, size_t pos, size_t n)
{
char *p1 = str + pos;
char *p2 = p1 + n;
char *l = str + strlen(str);
if(p1 < l)
{
if(p2 > l)
p2 = l;
while(*p2)
*p1++ = *p2++;
*p1 = *p2;
return 0;
}
return 1;
}
DSF
Is a pointer harmless as long as it's not dereferenced, or fed to a
function that dereferences it? After all, a pointer is just a number
until you try to access where it points to (at?) It would seem
logical that the answer to this is yes, but C can sometimes appear to
be "highly illogical," so I thought I'd ask here.
The reason I ask is that I'm creating a few string functions for my
personal library and I noticed that two of the pointers in the
following code may point to well beyond the string 'str' if 'pos' or
'n' are out of range.
/* deletes n chars from string str starting at position pos */
/* if pos > length of str, returns error */
/* if pos + n > length of str, deletes from pos to end of str */
int strdel(char *str, size_t pos, size_t n)
{
char *p1 = str + pos;
char *p2 = p1 + n;
char *l = str + strlen(str);
if(p1 < l)
{
if(p2 > l)
p2 = l;
while(*p2)
*p1++ = *p2++;
*p1 = *p2;
return 0;
}
return 1;
}
DSF