c - C 中的 Union 返回类型

标签 c

在下面的代码中,字符串“12345678901234567890”无法完整复制到 union 型变量中。这让我真的很困惑?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <time.h>

typedef union
{
    int i;
    long l;
    float f;
    double d;
    void *v;
    char *s;
    char c;
 } UType;

UType NewUType_s(char *s)
{
     UType temp;
     strcpy(temp.s, s);      // If we print temp.s and s here, both of them are "12345678901234567890
     return temp;
}

int main()
{
    UType m;
    m = NewUType_s("12345678901234567890");
    printf("%s\n", m.s);

    return 0;
 }

结果是:1234567890123456和一些特殊字符?

这个问题的解决方案可能是:

  • 方案一:对m使用malloc();

  • 解决方案 2:将 NewUType_s 样式更改为指针函数 UType *NewUType_s(char *s); 一切都会正常运行,

但是,有人知道上述程序没有正确结果的原因吗?

最佳答案

此代码的问题在于写入未初始化的指针是未定义的行为:temp.s 尚未分配可将字符串复制到其中的内存块,因此strcpy 写入您的程序不拥有的内存。

修复此代码很简单:在复制之前分配内存,如下所示:

UType NewUType_s(char *s)
{
     UType temp;
     temp.s = malloc(strlen(s)+1);
     strcpy(temp.s, s);
     return temp;
}

当然你需要释放内存以避免内存泄漏。

关于c - C 中的 Union 返回类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18579224/

相关文章:

c - 打开文件时出现错误

c++ - 在 C/C++ 中实现未知表模式的数据结构?

与指针程序的混淆(c编程)

c++ - 将全局变量添加到静态库以进行版本控制?

printf 后将变量内容转换为指针结果为 NULL

c - 如何在 Clion/Cmake 中链接外部库?

c - C中的异常读取位置

c - 我的(自定义)程序如何泄漏内存?我正在为 pset5 做准备

c++ - 这个错误是什么意思: "error: expected specifier-qualifier-list before ' type_name'"?

c - 在 Linux 上跨进程共享数据