My code (or the example from the book) seems to not work. I know it's the realloc function causing this, since I will allocate some memory to a set amount at the beginning. If I surpass the original amount I allocated, I will realloc() to increase the allocation.
The allocated memory is for a bunch of pointers, the more pointers I need, the more memory I need. These pointers will ultimately point to a string from an input. Regardless, the crashing occurs whenever I try to access the data at the string during a specific situation.
I set my COUNT (the amount I allocate originally) to let's say 5. It will crash after the sixth input. But, if I only have 5, no crashing. Thus, I believe this has something to do with realloc().
#define COUNT 5 // Initial number of strings
//code in between here
// ...
char** psTemp = NULL; // Temporary pointer to pointer to char
char* pTemp = NULL; // Temporary pointer to char
size_t str_count = 0; // Current string count
size_t capacity = COUNT; // Current maximum number of strings
// ...
if (str_count == capacity)
{
capacity += capacity / 4; // Increase capacity by 25%
if (!(psTemp = realloc(pS, capacity))) return 1;
pS = psTemp;
}
Above you can see my COUNT and realloc() function. I will update the allocation whenever I reach limit, when my current number of input (str_count) reaches the current allocation (capacity).
I've tried this in Visual Studio and Pelles C and both give me similar issues.
In Wisual Studio '13, it will crash after my 6th input, since my allocation is originally set to five.
In Pelles C, it will crash after my 8th input, why? I have no clue.
I ran it through the debugger, the realloc()
works, and the updated allocation works, yet it crashes.
I'm trying to self teach my self C but this book has too many of these weird errors!
Here is my code, I have realloc()
occur only once in my code: http://ideone.com/bY6CXk.