Reputation: 11
This code sometimes give me a Segmentation fault, why could this be?
void concatenarAlBuffer(char **destino, char caracter)
{
char matrizAux[1];
matrizAux[0]=caracter;
matrizAux[1]='\0';
(*destino) = realloc((*destino),2+(strlen((*destino))*sizeof(char)));
if ((*destino)==NULL)
{
perror("Error al reservar memoria\n");
exit(-1);
}
strcat((*destino),matrizAux);
}
Upvotes: 1
Views: 716
Reputation: 17648
char matrizAux[1]
hold only one character. Since you are accessing matrizAux[1]
, i.e. something out-of-bounds, you are corrupting the memory. This can result in the internal data of the runtime getting corrupted, which results in the segfault during the realloc()
, even though the realloc itself is correct.
Upvotes: 0
Reputation: 3706
You make
char matrizAux[1];
a 1-char long array.
And then you write to its' second element with
matrizAux[1]='\0';
This might or might not crash depending on what's behind your array in memory.
But it still looks like something's missing.
realloc
can reallocate only something that was previously malloc
- or calloc
-ated.
Trying to reallocate something that doesn't fulfill this condition gives you your error. And that's probably the true case here.
Upvotes: 1
Reputation: 21223
matrizAux
can only hold one character. You can't access matrizAux[1]
- it's out of bounds.
Declare matrizAux
like this:
char matrizAux[2];
Remember that an n
-elements array can be indexed in positions 0 up to (and including) n-1
.
Also, you don't need sizeof(char)
, because it it always 1. And parentheses around *destino
are useless in this case and make the code harder to read unnecessarily. Here's how I would change your code:
void concatenarAlBuffer(char **destino, char caracter) {
char matrizAux[2];
matrizAux[0]=caracter;
matrizAux[1]='\0';
*destino = realloc(*destino,2+strlen(*destino));
if (*destino == NULL) {
perror("Error al reservar memoria\n");
exit(-1);
}
strcat(*destino, matrizAux);
}
Upvotes: 1