【问题标题】:C language copying contents of a pointer byte by byte infinite loopC语言逐字节无限循环复制指针内容
【发布时间】:2018-10-11 14:21:02
【问题描述】:

我正在尝试将指针的内容逐字节复制到另一个指针,但我陷入了下面函数中的 for 循环。我相信这可能与 C 语言有关。任何线索为什么会发生这种情况?

void copy_COW(unsigned int pid, unsigned int vaddr) {
    //pid is the current process id,  vaddr is the double mapped page which has a fault
    dprintf("copying on write...\n"); dprintf("\n");

    //set fresh_page_index to perm writeable
    unsigned int writeable_perm =  PTE_P | PTE_W | PTE_U;   
    unsigned int* contents_to_copy;
    unsigned int* fresh_page_index;
    unsigned int i;

    //allocate fresh page
    fresh_page_index = (unsigned int*) alloc_page(pid, vaddr, writeable_perm);
    contents_to_copy = (unsigned int*) get_ptbl_entry_by_va(pid, vaddr);

    //fresh_page_index |= writeable_perm; //make page writeable, usable by user and present

    //copy contents at vaddr (dir, page) to fresh_page_index by looping thru
    for (i=0; i<4096 ;i++) 
    {
        //dprintf("i is %d \n", i); 
        char byteToCopy = contents_to_copy[i];

        fresh_page_index[i] = byteToCopy;
    }

    //update memory mapping in pdir to use fresh_page_index
    set_ptbl_entry_by_va(pid, vaddr, (unsigned int) fresh_page_index, writeable_perm);

}

【问题讨论】:

  • 即使不考虑无限循环,unsigned int -> char -> unsigned int 的复制行为在任何方面都是不正确的。
  • 程序卡住通常是访问冲突的标志。您应该使用调试器运行代码,您可能会遇到段错误。
  • 为什么不使用 memcpy 像 memcpy(fresh_page_index, contents_to_copy, 4096)?
  • 您的源指针和目标指针都是unsigned int* 类型,但您显然是在尝试复制字节(char byteToCopy = ...)。
  • 如果一页有 4096 字节,那么您写入的字节数越界,因为您尝试写入 4096 ints,这很可能会占用更多空间。

标签: c pointers memory


【解决方案1】:

在您的复制循环中,您正在读取 4096 个字符,并写入 4096 个整数。在循环中,读取的字符将符号扩展为整数并写入整数数组fresh_page_index

您要么需要调整类型定义,要么更简单地使用memcpy

【讨论】:

    猜你喜欢
    • 2016-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-16
    相关资源
    最近更新 更多