Reputation: 51543
This maybe endup being a silly question. I had done the following function:
char **getArrayOfStrings(int rows, int cols){
int i;
char **aux = malloc(rows * sizeof(char*));
for(i = 0; i < rows; i++)
aux[i] = malloc(cols+1);
return aux;
}
This would return me an Array of 'Strings', the chunk of code that matters is something like:
void f(...)
{
char **arrayOfStrings;
int i = 0;
arrayOfStrings = getArrayOfStrings(ROWS,COLS);
while(ch != '.' && sscanf (globalString,"%[^,|.]s", arrayOfStrings[i]) > 0)
{
globalString += strlen(arrayOfStrings[i++]) + 1;
ch = (*globalString-1); /** take the terminal characters */
}
freeMemory(&arrayOfStrings,ROWS);
}
where freeMemory is:
void freeMemory(char ***matrix, int size){
int i;
for(i = 0; i < size; i++) free((*matrix)[i]);
free(*matrix);
*matrix = NULL;
}
After finish my application, I run with valgrind to look for memory leaks (first time I am using valgrind).
And I get the following error:
Finding Invalid Pointer Use With Valgrind
==25012== Copyright (C) 2002-2011, and GNU GPL'd, by Julian Seward et al.
==25012== Using Valgrind-3.7.0 and LibVEX; rerun with -h for copyright info
==25012== Command: dist/Debug/GNU-MacOSX/app
==25012==
==25012== Invalid read of size 8
==25012== at 0x406445: f (Data.c:24)
==25012== by 0x400BE3: main (main.c:27)
I don't know what I am missing because the function getArrayOfStrings seems perfectly fine to me (well I could have used just one malloc but that is another problem).
EDIT.
The line that valgrind indicate is this one f (Data.c:24):
char **aux = malloc(rows * sizeof(char*));
Upvotes: 1
Views: 332
Reputation: 932
In my experience with valgrind, it shows exactly were illegal access is done. However, it seems that your output only shows the pointer that is related to the illegal access and where it is allocated.
Meaning we may be looking at the wrong line of code.
Looking closer at your while loop:
while(ch != '.' && sscanf (globalString,"%[^,|.]s", arrayOfStrings[i]) > 0)
{
globalString += strlen(arrayOfStrings[i++]) + 1;
ch = (*globalString-1); /** take the terminal characters */
}
If for some reason, on the final row ch
does not equal .
a illegal access will be done in arrayOfStrings[rows]
. Allocating rows+1 is a workaround. The contents are unknown and odds are there is no .
there, making the while condition evaluate to false with no illegal access.
I suggest either making sure a .
is present on the final iteration or including something like i < ROWS
in your while condition
Upvotes: 2