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.