J. Rautava J. Rautava - 11 months ago 43
C Question

What does memset(foo->a+foo->b, 0, 10) mean?

I have this piece of code in one library I'm using and I'm wondering what it does, since I'm having problems with memory I suppose this is the reason.

So the piece of code is following:

int new_size = foo->a_size + 10;
foo->a = realloc(foo->a, new_size*sizeof(struct items));
memset(foo->a+foo->a_size, 0, 10);


foo->a
is type
struct items*
and
foo->a_size
is type
int
.

First lines reallocate 10 blocks of new memory but now I'm wondering if
memset()
sets both
foo->a
and
foo->a_size
to 0 or should this set blocks from 11-20 to 0 in
foo->a
?
I have tried to run this code block on its own and receive only 'Segmentation fault'

EDIT:

Question was that does the
memset()
set both
foo->a
and
foo->a_size
to 0 or does it set blocks from offset
foo->a_size
to 0 in
foo->a
. The latter assumption was correct but I need to also fix the
memset()
so the last argument is
10*sizeof(struct items)
. I also edited variable names from
foo->b
to
foo->a_size
.

Answer Source

You are initializing 10 Bytes in foo->a(pointer) with foo->b(int) offset. In the other words you just initialized appended memory.

Example:

Lets assume foo->a is int* and is pointing to 5 ints continuous block.

+---+---+---+---+---+
| 0 | 0 | 0 | 0 | 0 |
+---+---+---+---+---+

You need 10 ints, so you will realloc that block to size 10 * sizeof(int) Bytes, but appended 5 * sizeof(int) Bytes are uninitialized.

+---+---+---+---+---+---+---+---+---+---+
| 0 | 0 | 0 | 0 | 0 | ? | ? | ? | ? | ? |
+---+---+---+---+---+---+---+---+---+---+

So by doing

memset(pointerToFirstByte + Offset, 0, 5 * sizeof(int));

You will init these appended bytes to 0.

+---+---+---+---+---+---+---+---+---+---+
| 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
+---+---+---+---+---+---+---+---+---+---+
                      ^---^---^---^---^------ Initialized to 0
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download