Reputation:
I have a program in which I try to read two lines of 40 characters. When something goes wrong or the program ends, I free array.
I'm getting an error message free(): invalid pointer Aborted (core dumped)
I think the problem is in the last cycle, but I can't solve it.
char *str = NULL;
size_t capacity = 0;
char **maska;
int rMaska=2, cMaska = 40;
maska =(char**)malloc (rMaska*sizeof(*maska));
for (int a = 0; a < rMaska; a++)
maska[a]=(char *) malloc (cMaska*sizeof(**maska));
i=0;
printf("Maska:\n");
while ( getline (&str, &capacity, stdin) != -1)
{
if (i==rMaska)
{
printf("incorrect entry.\n");
for (int i = 0; i < rMaska; i++)
free (maska[i]);
free(maska);
return 0;
}
if( strlen(str) != (unsigned int) cMaska )
{
printf("incorrect entry.\n");
for (int i = 0; i < rMaska; i++)
free (maska[i]);
free(maska);
return 0;
}
for (int i = 0; i < cMaska-1; i++)
{
if ( (str[i] != '#') && (str[i] != '.') )
{
printf("incorrect entry.\n");
for (int a = 0; a < rMaska; a++)
free (maska[a]);
free(maska);
return 0;
}
}
strcpy(maska[i], str);
i++;
}
free(str);
for (int i = 0; i < rMaska; i++)
free (maska[i]);
free(maska);
Upvotes: 0
Views: 2639
Reputation: 4431
You check that the string you input has strlen 40, and then if it has do a strcpy of the string to an array element whose allocated size is 40. But strcpy copies the trailing NUL too, that is it copies 41 characters. So you are, as the saying goes, doing a poo in the heap
Upvotes: 1
Reputation: 326
I suspect that the i
variable used in the while and for loops messed it all up.
I would define a different variable to use in the while loop (instead of i
), the fact that the for loops inside also use it is very confusing, and its also something that can later on create bugs.
And by the way you didn't free str
in case of incorrect entry.
Upvotes: 0