2

I have two C functions, which basically operate on a stack data structure. This one pushes a value of type OBJ which is actually just unsigned long to the top of the stack. The stack is also grown if necessary.

OBJ Quotation_push_(CzState *cz, CzQuotation *self, OBJ object)
{
    if ((self->size + 1) > self->cap) {
        self->items = (OBJ *)CZ_REALLOC(self->items, sizeof(OBJ) * (self->cap + 1) * 2);
        self->cap = (self->cap + 1) * 2;
    }
    self->items[self->size++] = object;
    return (OBJ)self;
}

The next function inserts an OBJ into an arbitrary position in the self->items array. Try as I might, it just won't work properly. I use Quotation_push_ here with a dummy value to get the automatic growth behavior. The problem is that I always see the CZ_NIL dummy value at the end of the array, with the item I'm trying to insert just overwriting what's in the position already. Here's what I've got so far:

OBJ Quotation_insert_(CzState *cz, CzQuotation *self, OBJ object, int pos)
{
    printf("have to move %d OBJ from %d to %d\n", self->size - pos, pos, pos + 1);
    Quotation_push_(cz, self, CZ_NIL);
    memmove(self->items + ((pos + 1) * sizeof(OBJ)), self->items + (pos * sizeof(OBJ)), sizeof(OBJ) * (self->size - pos));
    self->items[pos] = object;
    return (OBJ)self;
}

I'm not getting any segfaults or errors, it just doesn't work as expected. Any ideas?

Justin Poliey
  • 16,289
  • 7
  • 37
  • 48

1 Answers1

3

updated:

There are two problems, both in the call to memmove.

The first is an off-by-one error in the number of bytes that should be moved. The correct number would be:

sizeof(OBJ) * (self->size - pos - 1)

Omitting the -1 will actually move one too many bytes, placing your new CZ_NIL object past the end of the buffer.

The second problem is bigger, but more subtle. Adding integers to a pointer causes the compiler to perform pointer arithmetic, which automatically accounts for the size of the objects being pointed to. See this question for details. Here's the short version: self->items is an array of OBJ, so you don't need to include sizeof(OBJ) in the first two arguments to memmove.

Putting it all together, the proper function call would look like this:

memmove((self->items + pos + 1),
        (self->items + pos),
        sizeof(OBJ) * (self->size - pos - 1));
Community
  • 1
  • 1
e.James
  • 116,942
  • 41
  • 177
  • 214