Search code examples
ctcpkernelnic

How many memory copies occur when I read from TCP socket


My application runs read(sockfd, buffer, BUFFSIZE, 0). I know the kernel needs to do some copy work behind the scene. How many memory copies occur when buffer is allocated on the stack, and will it change if buffer is allocated on the heap?

Thanks.


Solution

  • Number of memory copies is always the same no matter if buffer is on heap or stack. Difference is only where is the memory located where you copy your data.

    In case of stack, you can enter to stack overflow and your program will have undefined behavior while if you do it on heap, you can enter to memory leaks if you don't free your memory after you don't need it anymore.