silly with memcpy()

M

Mark

Hi,

I have stuck with simple problem -- to copy number of bytes.

#define MAX_QUEUES 4

static int gweights[MAX_QUEUES] = { 1, 2, 3, 4 };
int foo (int *weights)
{
if (!weights)
return -1;

/* weights is actually an array defined by the caller */
memcpy(weights, gweights, MAX_QUEUES * sizeof weights);
return 0;
}

It looks to me that code is correct, i.e. it will copy (MAX_QUEUES * sizeof
weights) bytes from source to destination. Given that the size of pointer on
my system is always 32bit, then regadless of MAX_QUEUE value the resulting #
of bytes is correct. Is my reasoning right, or I'm missing something?
 
B

Ben Pfaff

Mark said:
#define MAX_QUEUES 4

static int gweights[MAX_QUEUES] = { 1, 2, 3, 4 };
int foo (int *weights)
{
if (!weights)
return -1;

/* weights is actually an array defined by the caller */
memcpy(weights, gweights, MAX_QUEUES * sizeof weights);

"sizeof weights" should be "sizeof *weights". You want the size
of an int, not the size of an int *.
 
L

Lew Pitcher

Mark said:
Hi,

I have stuck with simple problem -- to copy number of bytes.

#define MAX_QUEUES 4

static int gweights[MAX_QUEUES] = { 1, 2, 3, 4 };
int foo (int *weights)
{
if (!weights)
return -1;

/* weights is actually an array defined by the caller */
memcpy(weights, gweights, MAX_QUEUES * sizeof weights);
return 0;
}

Multiply by the sizeof the element type. The element type is int not int*,
so it should be
MAX_QUEUES * sizeof *weights

That one is "best practices"
or
MAX_QUEUES * sizeof (int)

That one works, but should be avoided in favour of the previous example.

Should some later alteration of the code change the declaration of weights
to some other type (i.e. from <<int *weights>> to <<long *weights>>, then
the programmer /must/ als change the <<MAX_QUEUES * sizeof (int)>> to
<<MAX_QUEUES * sizeof (long)>>

OTOH, with the same change to the declaration of weights, no change is
necessary for <<MAX_QUEUES * sizeof *weights>> as the compiler
automatically knows which type to use. This makes the program more
maintainable, and thus is counted as "best practices" wrt programming in C.
 
J

Jorgen Grahn

Thanks a lot.

For what? Already in your first posting, you seemed to know you had a
bug -- did sizeof(int*) when you meant sizeof(int) -- and your
question seemed to be if this would work if your pointers were 32-bit.

/Jorgen
 

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

Similar Threads

Adding adressing of IPv6 to program 1
Help with EXT3 Filesystem work 1
Is memcpy with len=0 a NOP? 16
memcpy question 4
memcpy() Behaviour 6
gcc inline memcpy 7
Help with Loop 0
memcpy() 3

Members online

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top