sizeof error

M

MarcSmith

Code
-------------------

void FullPath( char *newp, char *oldp, char *ext)
{
char *p = strchr( oldp, '.' );
if (p!=NULL) *p='\0';
snprintf( newp, sizeof(newp), "%s%s", oldp, ext );
}

-------------------


where sizeof had reported 4. i could use strlen() instead but it i
still going to truncate, but not as bad. i just have to add for th
extension as well. and it will work


-
MarcSmit
 
J

JayXie

The strlen() returns the length of a string by searching this string
for '\0'. While the keyword sizeof gets the size, so it should return
4 because each pointer costs 4 byte.
 
C

Chris Torek

void FullPath( char *newp, char *oldp, char *ext)
{
char *p = strchr( oldp, '.' );
if (p!=NULL) *p='\0';
snprintf( newp, sizeof(newp), "%s%s", oldp, ext );
}

The sizeof operator (yes, it is an operator like + or ~) returns
the size, in C bytes (which C also calls "char"s) [%], of its
operand. Here its operand is newp, and sizeof newp is the same as
sizeof(char *), which is typically four or eight today.

You need to tell snprintf() something other than 4 or 8 -- you
need to tell it how many bytes ("char"s) it is allowed to write
into newp[0], newp[1], newp[2], ..., newp[N-1]. That is, there
is some number N that defines the size of the area to which newp
points. What is N?

(*I* do not know what N is. The FullPath() function does not
receive N as a parameter. Where *will* N come from?)
... i could use strlen() ...

The strlen() function counts the number of chars (bytes) that can
be accessed sequentially before encountering a '\0' character.
Hence if newp[0] is currently 17 and newp[1] is currently 56 and
newp[2] is currently 0 and newp[3] is currently 41, strlen(newp)
will be 2. Clearly there is little if any relationship between
strlen(newp) and the number you need (N). (Of course, we can hope
that if you do call strlen(newp), the result is strictly less than
N -- if not, strlen() went past the N characters that it is "allowed"
to inspect, and inspected s9me other character(s) that it should
not have, using out-of-bounds array subscripts.)

[% Note that a "C byte" may be more than 8 bits. Some digital
signal processor C compilers have 16-bit or 32-bit "char"s. These
are still "bytes", on those machines, in the C language. To talk
about something that is always exactly 8 bits, networking folks
use the word "octet", to distinguish it from the 9 and 10 bit bytes
found on Univac and BBN-C-machines, and so on.]
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,156
Messages
2,570,878
Members
47,404
Latest member
PerryRutt

Latest Threads

Top