简体   繁体   中英

segmentation fault when freeing the buffer after sendto()

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);

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.

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);

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM