指向同一内存的两个指针和 realloc 失败

Two pointers pointing to a same memory and realloc failing

void container_row_change(struct brick_win_size *win, int character)
{
    row_container *container = &(win->container[win->current_row]);
    /*int offset = win->current_column;
    char *data = win->container[win->current_row]. data;
    if(offset < 0 || offset >= win->col)
        offset = container->size;

    data = realloc(data, win->container[win->current_row].size + 2 );
    memmove(&data[offset + 1], &data[offset], (win->container[win->current_row].size  - offset + 1));
    data[offset] = character;
    win->current_column++;
    container->size ++;
   */

   int offset = win->current_column;
   if(offset < 0 || offset >= win->col)
        offset = container->size;
   win->container[win->current_row].data = realloc(win->container[win->current_row]. data,      win->container[win->current_row]. size + 2);
   memmove(&(win->container[win->current_row].data[offset + 1]), &(win->container[win->current_row].data[offset]), win->container[win->current_row].size - offset + 1);
   win->container[win->current_row].data[offset] =character;
   win->current_column++;
   win->container[win->current_row].size ++;

}

谁能说出为什么注释行失败而不是另一行,尽管两者相同? 我想知道我分配指针和重新分配指针的方式是否有任何错误

在注释掉的代码中,你重新分配了本地指针 data 并且从不更新数据结构中的 .data 指针字段,所以它继续指向旧的(现在释放的)内存,当您尝试使用它时会导致损坏。

win->container[win->current_row].data = data;行添加到注释掉的代码中,它实际上等同于后面的代码。

请注意,在任何一种情况下,如果 realloc 失败,您都会崩溃——您应该检查失败并做一些适当的事情(可能打印一条错误消息并尝试正常退出)。