c - 全局变量的套接字更改地址

标签 c

我在下面有这段代码(非常非常简化)。

#include "test1.h"
#include <stdlib.h>
#include <stdio.h> 

extern struct1 *p;

int funct1()
{
    p = (struct1 *)malloc(sizeof(p));
    p->foo = 2;
    printf("value of foo in funct 1 is %d\n", p->foo);
    funct2();
}

int funct2()
{
    /*here do a lot of stuffs, mainly open socket,
      send some params, and close.
      Struct1 is not touched at all here*/
}

int funct3()
{
    printf("value of foo in funct 3 is %d\n", p->foo); 
}

int funct4()
{
    /*here listen to certain port, and execute funct4 
      if UDP is send to certain port*/
    funct3();
}

int main()
{
    funct1();
    funct3();
}

----测试1.h

typedef struct
{
    int foo;
}struct1;

struct1 *p = 0;

int funct1();
int funct2();
int funct3();
int funct4();

这个问题是我以某种方式损坏了地址:在 funct1 中,地址是例如:“20003001”,但是当我设置套接字监听某个端口并调用 funct3 时,foo变成“20003010”。它移动了一点。

为了简化, 1. 我在函数 1 中分配了 foo 的值 2. 调用 funct 2,用不使用 struct1 中的任何东西的 socket 做很多事情 3.如果消息到达某个端口,由调用funct 3的funct4处理 4. funct 3 打印 foo

唯一想到的是使用全局变量,但显然这很疯狂,因为它可能会在内存中发生损坏。我不能将指针从 funct 1,2,3.. 传递给 struct,因为还有很多其他函数,只有 funct 1 和 3 需要使用这个指针。

有没有人知道我如何访问 funct3 中的“foo”而不损坏全局变量?

谢谢你的建议

最佳答案

p = (struct1 *)malloc(sizeof(p));

仅分配 4 或 8 个字节(取决于系统/操作系统);指向结构的指针 的大小。您需要分配内存来保存结构本身:

p = malloc(sizeof(*p));

您也不需要转换 malloc 的结果。

关于c - 全局变量的套接字更改地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7958896/

相关文章:

c - allegro 中按键事件的错误

c - 我有一个链表,我想删除重复的值

c - 使用 fread() 挂起直到被杀死

c - 为什么“恢复”、“最小化”、“最大化”通知在不应该发送的情况下都被发送了?

c - 使用 GCC 和 MSVC 编译时的不同行为

C 函数参数的低级验证

c - 如何在数组中存储 1 000 000 000 个项目?

c - 如何处理 MacOS/X 10.8.x 中弃用的 Carbon 函数?

c - 文件交错、文件扫描、文件打印

c - 即时调整 char* 的大小 - 为什么此代码*有效*?