simple Pointer initialization

前端 未结 7 1770
傲寒
傲寒 2020-12-13 07:14

It has been a while that I used pointers and I just wanna quickly check how I can initialize an integer pointer?

a) int *tmpPtr = 0;

b) int *tmpPtr = null;
         


        
7条回答
  •  佛祖请我去吃肉
    2020-12-13 08:05

    Reply to your question in EDIT:

    • When you do this :

      int tmp = 0;
      int *tmpPtr = &tmp;
      Mem::Copy((void*)tmpPtr, basepointer(), sizeof(int));
      

    tmpPtr is pointing to the address of variable tmp and it is in the stack. And notice that the "safe area" pointed by tmpPtr is the size of tmp (which is 4 in some machine and 2 in others). If you were to copy more than sizeof(int) bytes to tmpPtr you will risk of crashing the stack.

    • When you do this :

      int *tmpPtr = 0;
      Mem::Copy((void*)tmpPtr, basepointer(), sizeof(int));
      

    The value of tmpPtr is 0 ,so you will get a segment fault. ,which is a memory protection mechanism offered by the operation system. For example , you are not allowed to write any virtual address that is less than 4K.

提交回复
热议问题