简体   繁体   English

从 unsigned int 到 char 指针的类型转换中的分段错误

[英]Segmentation Fault in typecasting from unsigned int to char pointer

I'm new to c.我是 c 的新手。 Just learning.只是学习。 What i am trying to do is initialize a variable type of unsigned int and then store address of an char type array in it and after that I am trying to use int as a pointer and print the array using the unsigned int but I'am getting segmentation fault, I don't know why?我想要做的是初始化一个 unsigned int 变量类型,然后在其中存储一个 char 类型数组的地址,然后我尝试使用 int 作为指针并使用 unsigned int 打印数组,但我得到分段错误,我不知道为什么? It's printing value of memory address of char type array.它是char类型数组的内存地址的打印值。 But not the actual values at memory addresses.但不是内存地址的实际值。 Can someone please help?有人可以帮忙吗?

#include <stdio.h>

int main()
{
    char char_arr[4] = {'a', 'b', 'c', 'd'};
    int i;

    unsigned int hackyPointer;
    hackyPointer = (unsigned int) char_arr;

    for (i = 0; i < 4; i++)
    {
        printf("[hacky Pointer] now points to %p which contains value %c\n",hackyPointer, *((char *) hackyPointer));
        hackyPointer += sizeof(char);
    }

}

The problem is that you are trying to fit a bigger number than int can store, that is if you are running x64 .问题是您试图适应比int可以存储的更大的数字,也就是说,如果您正在运行x64

In 64 bit systems, pointers have a size of 8 bytes and int is usually 4 bytes.在 64 位系统中,指针的大小为 8 个字节,而int通常为 4 个字节。 Pointer addresses work like numbers so when you cast the pointer to int , the address will be truncated.指针地址像数字一样工作,因此当您将指针转换为int ,地址将被截断。

Casting the int back to a pointer it will now contain some other address that does not belong to your program which can result in a access violation, or in other words, a segmentation fault.int回指针,它现在将包含一些不属于您的程序的其他地址,这可能导致访问冲突,或者换句话说,分段错误。

Use a bigger int to hold the address, cast it to an int pointer or use uintptr_t type which is guaranteed to be big enough to hold the address.使用更大的int来保存地址,将其转换为int指针或使用uintptr_t类型,该类型保证足够大以保存地址。

What you are trying to do is the following你正在尝试做的是以下

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

int main()
{
    char char_arr[4] = {'a', 'b', 'c', 'd'};
    int i;

    uintptr_t hackyPointer;
    hackyPointer = (uintptr_t) char_arr;

        for (i = 0; i < 4; i++)
        {
            printf("[hacky Pointer] now points to %p which contains value %c\n",( void * )hackyPointer, *((char *) hackyPointer));
            hackyPointer += sizeof(char);
        }
}        

The program output is程序输出是

[hacky Pointer] now points to 0x7ffff86d4224 which contains value a
[hacky Pointer] now points to 0x7ffff86d4225 which contains value b
[hacky Pointer] now points to 0x7ffff86d4226 which contains value c
[hacky Pointer] now points to 0x7ffff86d4227 which contains value d

You have to use an integer type that is able to contain values of pointers.您必须使用能够包含指针值的整数类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM