I have a simple programa that populates a 2D dynamic char array. Allocation works as usual. My problem relies on freeing arrays. I'm using pure C on VC++ 2008.
This is the piece of code when I allocate and initializes my arrays:
char** messsages = (char**)malloc(5*sizeof(char*));
initValorArrayMsgs(messsages, 5);
insertMsgToArray(5, messsages , "Test message.");
void insertMsgToArray(int totalLines, char** msgsArray, const char* msgToInsert)
{
int line = 0;
int size= strlen(msgToInsert);
for(; line < totalLines; line ++)
{
if(strlen(msgsArray[line ]) == 0)
{
msgsArray[line ] = (char*)malloc(sizeof(char) * size);
strcpy(msgsArray[line], msgToInsert);
break;
}
}
}
And this is the code where I free my arrays
void freeArrayMsgs(char** arry, int lines)
{
int i = 0;
for(; i < lines; i++)
{
if(strlen(arry[i]) == 0){
break;
}
free(arry[i]);
}
free(arry);
}
When program try to free the first array, it raises a Heap Corruption Exception.
Reading some posts on SO, I'm corretly freeing my array. So, why I'm getting the hep corruption exception?