Malloc corrupting already malloc'd memory in C
- by Kyte
I'm currently helping a friend debug a program of his, which includes linked lists. His list structure is pretty simple:
typedef struct nodo{
int cantUnos;
char* numBin;
struct nodo* sig;
}Nodo;
We've got the following code snippet:
void insNodo(Nodo** lista, char* auxBin, int auxCantUnos){
printf("*******Insertando\n");
int i;
if (*lista) printf("DecInt*%p->%p\n", *lista, (*lista)->sig);
Nodo* insert = (Nodo*)malloc(sizeof(Nodo*));
if (*lista) printf("Malloc*%p->%p\n", *lista, (*lista)->sig);
insert->cantUnos = auxCantUnos;
insert->numBin = (char*)malloc(strlen(auxBin)*sizeof(char));
for(i=0 ; i<strlen(auxBin) ; i++)
insert->numBin[i] = auxBin[i];
insert-numBin[i] = '\0';
insert-sig = NULL;
Nodo* aux;
[etc]
(The lines with extra indentation were my addition for debug purposes)
This yields me the following:
*******Insertando
DecInt*00341098->00000000
Malloc*00341098->2832B6EE
(*lista)-sig is previously and deliberately set as NULL, which checks out until here, and fixed a potential buffer overflow (he'd forgotten to copy the NULL-terminator in insert-numBin).
I can't think of a single reason why'd that happen, nor I've got any idea on what else should I provide as further info.
(Compiling on latest stable MinGW under fully-patched Windows 7, friend's using MinGW under Windows XP. On my machine, at least, in only happens when GDB's not attached.)
Any ideas? Suggestions? Possible exorcism techniques? (Current hack is copying the sig pointer to a temp variable and restore it after malloc. It breaks anyways. Turns out the 2nd malloc corrupts it too. Interestingly enough, it resets sig to the exact same value as the first one).