【问题标题】:Linux <-> Windows Storing an address of stringLinux <-> Windows 存储字符串地址
【发布时间】:2014-10-21 21:29:14
【问题描述】:

我在 Linux 上编写应用程序时遇到了严重问题。 我有这个代码

#include <stdio.h>

int main()
{
    char ar[10][10];
    strcpy(ar[1], "asd");
    strcpy(ar[2], "fgh");

    int test[2];
    test[1] = (int)ar[1];
    printf("%s %x | %s %x\n\n", ar[1], ar[1], test[1], test[1]);

    return 0;
}

它在 Windows 上运行良好,但是当我想在 Linux 上运行它时,我得到了 分段错误或未经授权访问内存。

【问题讨论】:

标签: c linux windows gcc


【解决方案1】:

您的程序调用了未定义的行为。它假定指针将适合int,这不是必需的。通常指针适合 Unix 机器,但在 Windows 上会失败;但如果需要进行此类转换,则应使用适当的整数类型,例如 stdint.h 中的 intptr_t。请注意,严格来说,整数必须在传递给 printf 之前转换回指针类型。

使用指向printf 的指针类型和足够大的整数类型会导致正确的行为:http://ideone.com/HLExMb

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

int main(void)
{
    char ar[10][10];
    strcpy(ar[1], "asd");
    strcpy(ar[2], "fgh");

    intptr_t test[2];
    test[1] = (intptr_t)ar[1];
    printf("%s %x | %s %x\n\n", ar[1], ar[1], (char*)test[1], (char*)test[1]);

    return 0;
}

请注意,尽管将指针转换为整数类型通常是不受欢迎的,并且可能会导致程序错误。除非出于某种原因绝对需要这样做,否则不要去那里。当您刚开始使用 C 语言时,您不太可能需要这样做。

【讨论】:

  • 附带说明,即使没有 -Wall 选项,gcc 的输出也会对此发出警告。
猜你喜欢
  • 1970-01-01
  • 2011-03-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-25
  • 1970-01-01
  • 2021-11-02
  • 1970-01-01
相关资源
最近更新 更多