Reputation: 1089
I have this code below (very very simplified).
#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();
The problem with this is that I somehow got a corrupt of the address : in funct1 the address is for example :"20003001", but by the time I set the socket that listen to a certain port and call funct3, the foo becomes "20003010". it shifted a little bit.
So to simplify, 1. I assigned value of foo in funct 1 2. Call funct 2, do a lot of stuffs with socket that does not use anything from struct1 3. If a message comes to a certain port, handled by funct4 that call funct 3 4. funct 3 print foo
The only thing that comes to mind is using a global variable, but apparently this is crazy as it can happen a corrupt in the memory. I can't pass the pointer to struct from funct 1,2,3.. as there are tons of other functions, and only funct 1 and 3 needs to use this pointer.
Does anyone has any idea, how I can access "foo" in funct3 without any corruption in the global variable?
Thank you for any advice
Upvotes: 0
Views: 474
Reputation: 76908
p = (struct1 *)malloc(sizeof(p));
Only allocates 4 or 8 bytes (system/OS dependent); the size of a pointer to a struct. You need to allocate memory to hold the structure itself:
p = malloc(sizeof(*p));
You also don't need to cast the result of malloc.
Upvotes: 2
Reputation: 70909
p is a pointer, so if you want to allocate a struct1, you need to do
p = (struct1 *)malloc(sizeof(struct1));
While it is possible that you are allocating something of an equivalent size, it's not advisable to "change types" or even to obfuscate types during memory allocation. When it does go wrong, bad things really do happen.
Upvotes: 1