【发布时间】: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,这很可能会占用更多空间。