2017-09-17 39 views
-1
#include <stdio.h> 
#include <sys/types.h> 
#include <unistd.h> 
#include <stdlib.h> 

void forkexample() 
{ 
    int x = 1; 

    if (fork() == 0) 
     { 
      //printf("this is Child "); 
      ++x; 
      printf("addr of x=%p\n",&x); 
      int* arr1=(int*)malloc(sizeof(int)*5); 
      *arr1=5; 
      printf("Addr of child arr1=%p arr1[0]=%d\n",&arr1,arr1[0]); 
     } 
    else 
    { 
     //printf("this is parent "); 
     --x; 
     printf("addr of x=%p\n",&x); 
     int* arr2=(int*)malloc(sizeof(int)*5); 
     *arr2=6; 
     printf("Addr of parent arr2=%p arr2[0]=%d\n",&arr2,arr2[0]); 
    } 
} 
int main() 
{ 
    forkexample(); 
    return 0; 
} 

screenshot of output相同逻辑地址的叉()

为什么& ARR1 = & ARR2?

我知道操作系统将使用写时复制(COW)方法为子进程创建新的地址空间,'&'给出逻辑地址,但这里我们在这里动态创建2个不同的数组。

回答

2

arr1arr2不是数组,它们是指针。您在forkexample范围内打印局部变量的地址,就像x一样。如果要查看由malloc返回的内存地址,则需要printf("%p", arr1),而不是&arr1

假定编译器决定使用相同的存储空间来存储arr1arr2,因为变量的范围不重叠。您可以通过代码更改为验证这一理论:

void forkexample(void) 
{ 
    int x = 1; 
    { 
     ++x; 
     printf("addr of x=%p\n", (void *)&x); 
     int *arr1 = malloc(sizeof(int)*5); 
     *arr1 = 5; 
     printf("Addr of child arr1=%p arr1[0]=%d\n", (void *)&arr1, arr1[0]); 
    } 
    { 
     --x; 
     printf("addr of x=%p\n", (void *)&x); 
     int *arr2 = malloc(sizeof(int)*5); 
     *arr2 = 6; 
     printf("Addr of parent arr2=%p arr2[0]=%d\n", (void *)&arr2, arr2[0]); 
    } 
} 

...看看arr1arr2是否仍然有相同的地址。


旁注:printf%p需要void *,而不是int *int **(这是你传递什么)。您需要演员:printf("%p\n", (void *)&arr1);

+0

感谢关于%p,但在父进程和子进程中,无论使用malloc()分配多大的大小,sizeof运算符都会给出恒定大小= 0x4(即int的大小)。 –

+0

@ShashankRao然后我想这就是你平台上指针的大小。 – melpomene

+0

int * arr1 = malloc(sizeof(int)* 5),但在正常情况下,它应该给5 * sizeof int即5 * 4 = 20B –