Reputation: 1637
I get a segmentation fault when freeing the buffer 'pkt'
after the function sendto()
u_char* create_pkt(u_char* pkt)
{
....
pkt = (u_char *)malloc(40);
...
return pkt
}
int main()
{
....
u_char* pkt;
create_pkt(pkt);
if (sendto(sd, pkt, 40, 0, (struct sockaddr *)&sin, sizeof(struct sockaddr)) < 0)
free(pkt);
}
the debugging information shows:
Program received signal SIGSEGV, Segmentation fault.
0x0000003897482864 in __GI___libc_free (mem=0x7fffffffe010) at malloc.c:2986
what is wrong with this? thanks!
2986 ar_ptr = arena_for_chunk(p);
2986 ar_ptr = arena_for_chunk(p);
Upvotes: 1
Views: 425
Reputation: 46579
The create_pkt
function returns the newly allocated value, so you'll need to use that in the calling function.
pkt =
create_pkt(pkt);
Otherwise the program will just ignore the pointer to the allocated memory and use the original (unassigned) value of pkt
.
Edit: if you want to use the argument as something to assign the value to, you can write something like this
void create_pkt(u_char** pkt)
{
....
*pkt = (u_char *)malloc(40);
...
}
and call it with
create_pkt(&pkt);
but I can't really recomment that.
Upvotes: 2
Reputation: 5163
You are trying to allocate the memory and loosing the allocated reference. So the garbage is sent and then attempt to release kills it.
u_char* create_pkt()
{
u_char* pkt;
....
pkt = (u_char *)malloc(40);
...
return pkt;
}
int main()
{
....
u_char* pkt;
pkt = create_pkt();
if (sendto(sd, pkt, 40, 0, (struct sockaddr *)&sin, sizeof(struct sockaddr)) < 0)
free(pkt);
}
Upvotes: 0
Reputation: 63200
u_char* create_pkt(u_char* pkt)
copies your pointer and then allocates it inside, but only allocates the copy. When the function returns your original pointer is still as it was, unallocated.
Now you can either return a pointer from this function or pass in a double pointer u_char** pkt
and assign the address of pkt
to it.
pkt = create_ptk(pkt);
now you'll have allocated pkt.
for double pointer version this is how you'd call it:
create_pkt(&pkt);
Upvotes: 0