Thread: Misunderstood static local behaviour in pthread application

  1. #1
    Registered User
    Join Date
    Jul 2009
    Posts
    1

    Misunderstood static local behaviour in pthread application

    Hi all,

    I am struggling to understand why I am seeing the variable "buffer" clobbered when two threads are invoking the following function. My understanding says that buffer is treated as being allocated on the heap, however when reading the buffer on the other end of the socket the data is clearly clobbered.

    Note the mutex is needed as two threads are sharing a common file descriptor, "fd".

    If I remove the "static" keyword the program runs without error.

    The buffer size is largish, approximately 800K, however nowhere near the stack size on the 64-bit SPARC architecture on which the program is run (2MB). The space consumed by other locals is negligible.

    Code:
    int socket_write(int fd, hdr header, int body_size, void *body)
    {
      static char buffer[MAX_MSG_SIZE];
      int status;
    
      pthread_mutex_lock(&fd_mutex);
    
      // do memcpy()'s into buffer for the passed msg header and body
      // and then write it out on the socket
    
      pthread_mutex_unlock(&fd_mutex);
    
      return status;
    }
    Last edited by Tristan; 07-21-2009 at 03:42 AM.

  2. #2
    Registered User
    Join Date
    Jul 2009
    Location
    Mumbai
    Posts
    1
    Hi Tristan,
    I use to avoid static variables until its value is needed for later use. I mean like in ur case its just a buffer, which we generally use for storing temporary data, need not to be static. A static variable blocks memory till the process runs. so i think your programm is going out of memory. For such large memory requirement I use malloc or calloc.

  3. #3
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    You would need to post your actual function, not a snipped and summarised version of it.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Screwy Linker Error - VC2005
    By Tonto in forum C++ Programming
    Replies: 5
    Last Post: 06-19-2007, 02:39 PM
  2. Best choise for a local application database
    By gogic in forum C# Programming
    Replies: 2
    Last Post: 04-04-2006, 07:08 AM
  3. Intercepting Data Bound for Local Application from Remote Server
    By maththeorylvr in forum Networking/Device Communication
    Replies: 2
    Last Post: 11-29-2005, 01:57 AM
  4. Folding@Home Cboard team?
    By jverkoey in forum A Brief History of Cprogramming.com
    Replies: 398
    Last Post: 10-11-2005, 08:44 AM
  5. pointers
    By InvariantLoop in forum C Programming
    Replies: 13
    Last Post: 02-04-2005, 09:32 AM