Unusual 'malloc()' behaviour...

This is a discussion on Unusual 'malloc()' behaviour... within the C Programming forums, part of the General Programming Boards category; Take a look at the following c function: Code: struct neuron* new_neuron(char* name, boolean state, float threshold) { struct neuron* ...

  1. #1
    Registered User
    Join Date
    Mar 2009
    Posts
    2

    Unusual 'malloc()' behaviour...

    Take a look at the following c function:

    Code:
    struct neuron*
    new_neuron(char* name, boolean state, float threshold)
    {
      struct neuron* current = malloc((size_t) sizeof(struct neuron*));
      struct synapse** spare = malloc((size_t) sizeof(struct synapse**)); /* <-- #2 */
      
      // If there's no room for the neuron, report to standard error and exit.
      if (current == NULL)
      {
        fprintf(stderr, "ERROR: THE MALLOC() FUNCTION FAILED ON A NEURON!\n");
        fprintf(stderr, "Named '%s'\n.", name);
        exit(NO_MEMORY_FOR_NEURON_ERROR);
      }
      
      // Set aside memory to store the synapses.
      (*current).dendrites = malloc((size_t) sizeof(struct synapse**)); /* <-- #1 */
      (*current).terminals = malloc((size_t) sizeof(struct synapse**));
      
      // If there's no room for the synapses, report to standard error and exit.
      if ((*current).dendrites == NULL || (*current).terminals == NULL)
      {
        fprintf(stderr, "ERROR: THE MALLOC() FUNCTION FAILED ON A SYNAPSE!\n");
        fprintf(stderr, "Within '%s'\n.", name);
        exit(NO_MEMORY_FOR_SYNAPSE_ERROR);
      }
      
      // Define and return a neuron.
      (*current).name = name;
      (*current).state = state;
      (*current).threshold = threshold;
      (*current).dendrite_count = 0;
      (*current).terminal_count = 0;
      return current;
    }
    It works just fine and does exactly what I need it to, but for some peculiar reason, the first 'struct synapse**' variable I apply 'malloc()' to, showcases some very unusual behaviour and doesn't work properly, despite the fact that all subsequent ones work fine.

    Initially, the line marked "#1" was the first time I applied 'malloc()' to a 'struct synapse**', but when that resulted in weird behaviour, I added the line marked "#2" in order to salvage the rest of the function with a quick-and-dirty solution. That particular variable ("spare") doesn't do anything, so the fact that it's broken is irrelevant, but I'm really curious why it's broken! Someone enlighten me please.

  2. #2
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,185
    You are acting as though current has enough memory to store a struct neuron. Since you allocate enough memory for a pointer to a struct neuron, that assumption is incorrect. You should allocate the correct size in your line #1 (the typical way is to do sizeof(*current), but you can use the type name itself).

  3. #3
    Registered User
    Join Date
    Jun 2005
    Posts
    6,620
    Or, to put it in slightly more understandable terms.
    Code:
      struct neuron* current = malloc((size_t) sizeof(struct neuron*));
      struct synapse** spare = malloc((size_t) sizeof(struct synapse**));
    The red asterixes need to be removed. You haven't specified the types of members of a struct neuron, but I assume a similar mistake has been made in the later malloc() calls as well.

    Optionally, the size_t conversions may also be removed (as sizeof() is supposed to yield a result of type that can be stored in a size_t anyway).

    Also, instead of "(*current).name" use "current->name". That is what the -> operator is for.
    Right 98% of the time, and don't care about the other 3%.

    If I seem grumpy or unhelpful in reply to you, or tell you you need to demonstrate more effort before you can expect help, it is likely you deserve it. Suck it up, Sunshine, and read this, this, and this before posting again.

  4. #4
    Registered User
    Join Date
    Mar 2009
    Posts
    2
    Ha ha, thank you both. I just CANNOT believe I made such a hideously simple mistake! I should have known better.

    Why was I able to get away with the exact same thing the second, third, or nth time though? That's probably why it snuck under my radar...

  5. #5
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    Quote Originally Posted by sanjav View Post
    Why was I able to get away with the exact same thing the second, third, or nth time though? That's probably why it snuck under my radar...
    Memory errors can be brutal because it all depends how the compiler decided to assemble all the chunks. It is totally possible (in fact very easy) to have more than a thousand lines of code all running smoothly after weeks of work, and then when compiled on a different machine -- same OS, same compiler but slightly different compiler version -- and all of a sudden it is full of bugs that "slipped under your radar".

    It has been said many times many ways -- the fact that something worked for you a few times at home is no evidence that it is being done correctly. The use of memory profiling software may help -- but I would bet the best way is to just always be writing small "experimental" programs when you first use a new technique. That way, you have a number of contexts in which misunderstanding may expose itself. It is very tempting, when you are working on a project, to just forge ahead once you think you've figured out how to do what you want without testing the method somewhere outside the project. But I guarantee your programming experience goes up everytime you find yourself having to type "int main" again.
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. malloc + segmentation fault
    By ch4 in forum C Programming
    Replies: 5
    Last Post: 04-07-2009, 04:46 PM
  2. Wierd Malloc Problem
    By mohankarthik in forum C Programming
    Replies: 11
    Last Post: 09-17-2008, 03:14 PM
  3. Is there a limit on the number of malloc calls ?
    By krissy in forum Windows Programming
    Replies: 3
    Last Post: 03-19-2006, 12:26 PM
  4. Malloc and calloc problem!!
    By xxhimanshu in forum C Programming
    Replies: 19
    Last Post: 08-10-2005, 06:37 AM
  5. malloc() & address allocation
    By santechz in forum C Programming
    Replies: 6
    Last Post: 03-21-2005, 09:08 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21