我在下面有這個代碼(非常非常簡化)。全局變量的套接字更改地址
#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();
}
---- test1.h
typedef struct
{
int foo;
}struct1;
struct1 *p = 0;
int funct1();
int funct2();
int funct3();
int funct4();
這樣做的問題是,我不知怎麼損壞地址:在funct1的地址,例如:「20003001」,但當我設置偵聽某個端口並調用funct3的套接字時,foo變爲「20003010」。它轉移了一點點。
因此簡化, 1.我在函數的foo賦值1 2.通話本功能2,做了很多東西與插座不從struct1 3.使用任何如果消息達到一定端口,由funct4調用功能3 4.功能3打印foo
唯一想到的是使用全局變量,但顯然這是瘋狂的,因爲它可能發生在內存中的損壞。我無法將指針從funct 1,2,3傳遞給struct,因爲有很多其他函數,只有funct 1和3需要使用這個指針。
有沒有人有任何想法,我怎麼可以在funct3中訪問「foo」而不會在全局變量中發生任何損壞?
感謝您的任何意見
我認爲你的結構是八字節的大小?因爲如果是這樣的話,那麼funct1()的某個地方會被再次調用並重置* p。我不認爲這是內存腐敗和其他問題一樣,如果p只是嚴格用於funct1和funct3 ...我建議將它重命名爲其他地方不用的東西,以便您可以確定p是否已在別處設置。 –
@AhmedMasud:這是一個簡化的函數,實際的代碼由一個列表和一些其他參數組成。但問題在於訪問全局變量,在套接字被編譯後改變其地址 – heike
好吧,那麼你可以分享套接字開放代碼嗎? –