Hi all,
with the below code valgrind tells me i am leaking memory, does anyone have an idea?
my main intention here is to have an array of strings (fixed string lengh but dynamic number of strings) which i can pass back and forth between main and other functions. (without decrlaring it global)
Code:
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#define MAXLINES 65534
#define BUFSIZE 1024
#define BUFROW 80
#define ALLOC_ERR {fprintf(stderr,"Error allocating memory\n"); exit(EXIT_FAILURE);}
int lIndex;
char **extendArr(char **tempArr)
{
int i, len;
if(lIndex==0)
{
tempArr = malloc(BUFROW * sizeof(char *));
if(tempArr ==NULL)
ALLOC_ERR
for(i=0; i< BUFROW; i++)
{
tempArr[i]=(char *) malloc(BUFSIZE * sizeof(char));
tempArr[i]="aaa";
}
}
return(tempArr);
}
int readLine(char **tempArr)
{
int i;
//if(extendArr(tempArr) == NULL)
// ALLOC_ERR
for(i=0;i<BUFROW; i++)
{
tempArr[i]="aaa";
// fprintf(stdout,"%d\t%s\n",i,tempArr[i]);
}
return(1);
}
int main(int argc, char **argv)
{
int i;
char **tempArr;
// not checking for NULL here, its just a test-setup because of the array passing-around
tempArr=malloc(BUFROW * sizeof(char *));
for (i=0; i< BUFROW; i++)
tempArr[i]=malloc(BUFSIZE*sizeof(char));
readLine(tempArr);
for (i=0; i< BUFROW; i++)
{
fprintf(stdout,"%d\t%s\n",i,tempArr[i]);
//readLine(tempArr);
}
for(i=0;i < BUFROW; i++)
free(tempArr[i]);
free(tempArr);
return(1);
}
==12738== Invalid free() / delete / delete[]
==12738== at 0x40282A3: free (in /usr/lib/valgrind/vgpreload_memcheck-x86-linux.so)
==12738== by 0x405F002: (below main) (in /lib/libc-2.14.1.so)
==12738== Address 0x80487d9 is not stack'd, malloc'd or (recently) free'd
==12738==
==12738==
==12738== HEAP SUMMARY:
==12738== in use at exit: 81,920 bytes in 80 blocks
==12738== total heap usage: 81 allocs, 81 frees, 82,240 bytes allocated
==12738==
==12738== Searching for pointers to 80 not-freed blocks
==12738== Checked 48,820 bytes
==12738==
==12738== 81,920 bytes in 80 blocks are definitely lost in loss record 1 of 1
==12738== at 0x402913D: malloc (in /usr/lib/valgrind/vgpreload_memcheck-x86-linux.so)
==12738== by 0x405F002: (below main) (in /lib/libc-2.14.1.so)
==12738==
==12738== LEAK SUMMARY:
==12738== definitely lost: 81,920 bytes in 80 blocks
==12738== indirectly lost: 0 bytes in 0 blocks
==12738== possibly lost: 0 bytes in 0 blocks
==12738== still reachable: 0 bytes in 0 blocks
==12738== suppressed: 0 bytes in 0 blocks
the invalid free and the mem loss does not occur when i comment out
tempArr[i]="aaa";
thanks a lot