我正在读这本黑客攻击的艺术书,下面的代码似乎会抛出以下错误

问题描述 投票:0回答:1

错误

pointer_types5.c: In function ‘main’:
pointer_types5.c:11:28: warning: cast from pointer to integer of different size [-Wpointer-to-int-cast]
   11 |         hacky_nonpointer = (unsigned int) char_array;
      |                            ^
pointer_types5.c:15:33: warning: cast to pointer from integer of different size [-Wint-to-pointer-cast]
   15 |             hacky_nonpointer, *((char *) hacky_nonpointer));
      |                                 ^
pointer_types5.c:19:28: warning: cast from pointer to integer of different size [-Wpointer-to-int-cast]
   19 |         hacky_nonpointer = (unsigned int) int_array;
      |                            ^
pointer_types5.c:23:33: warning: cast to pointer from integer of different size [-Wint-to-pointer-cast]
   23 |             hacky_nonpointer, *((int *) hacky_nonpointer));
      |   

代码

#include <stdio.h>

int main() {
    int i;

    char char_array[5] = {'a', 'b', 'c', 'd', 'e'};
    int int_array[5] = {1, 2, 3, 4, 5};

    unsigned int hacky_nonpointer;

    hacky_nonpointer = (unsigned int) char_array;

    for(i=0; i < 5; i++) { // iterate through the int array with the int_pointer
        printf("[hacky_nonpointer] points to %p, which contains the char '%c'\n",
            hacky_nonpointer, *((char *) hacky_nonpointer));
        hacky_nonpointer = hacky_nonpointer + sizeof(char);
    }

    hacky_nonpointer = (unsigned int) int_array;
    
    for(i=0; i < 5; i++) { // iterate through the int array with the int_pointer
        printf("[hacky_nonpointer] points to %p, which contains the integer %d\n",
            hacky_nonpointer, *((int *) hacky_nonpointer));
        hacky_nonpointer = hacky_nonpointer + sizeof(int);
    }
}
  
c pointers casting segmentation-fault warnings
1个回答
0
投票

代码无效且具有未定义的行为。

例如,

unsigned int
类型的对象通常不能存储指针类型的值,因为它们的大小不同,如第一个警告所述。

此外,转换说明符

%p
旨在输出指针类型的值
void *
而不是输出整数。再次调用未定义的行为。

您可以通过以下方式更改您的程序

#include <stdio.h>
#include <stdint.h>
#include <inttypes.h>

int main( void ) 
{
    enum { N = 5 };
    char char_array[N] = {'a', 'b', 'c', 'd', 'e'};
    int int_array[N] = {1, 2, 3, 4, 5};

    uintptr_t hacky_nonpointer;

    hacky_nonpointer = ( uintptr_t )char_array;

    for ( int i = 0; i < N; i++ ) 
    { // iterate through the int array with the int_pointer
        printf("[hacky_nonpointer] points to %" PRIuPTR ", which contains the char '%c'\n",
            hacky_nonpointer, *( char * )( void * )hacky_nonpointer );
        hacky_nonpointer = hacky_nonpointer + sizeof(char);
    }

    hacky_nonpointer = ( uintptr_t )int_array;
    
    for ( int i = 0; i < N; i++ ) 
    { // iterate through the int array with the int_pointer
        printf("[hacky_nonpointer] points to %" PRIuPTR ", which contains the integer %d\n",
            hacky_nonpointer, *( int * )( void * )hacky_nonpointer );
        hacky_nonpointer = hacky_nonpointer + sizeof(int);
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.