So, I'm having trouble in allocating memory for a char ***
type variable. My objective is to create a matrix of strings and the code I currently have for memory allocation is the following:
char ***matrix;
matrix = calloc(n*MAX_STR, sizeof(char**));
for(z = 0; z < n; z++) {
matrix[z] = calloc(n, sizeof(char*));
for(i = 0; i < MAX_STR; i++) {
matrix[z][i] = calloc(MAX_STR, sizeof(char));
}
}
I have successfully allocated memory for an array of strings, using this:
char **list;
list = calloc(n, sizeof(char *));
for (j = 0; j < n; j++){
list[j] = calloc(MAX_STR, sizeof(char));
}
but I'm now having problems with the matrix.
Running the program with --leak-check=full on Valgrind gives me the following message:
==5126== Invalid write of size 8
==5126== at 0x400B9F: createmat (proj.c:100)
==5126== by 0x401598: main (proj.c:237)
==5126== Address 0x5210878 is 0 bytes after a block of size 72 alloc'd
==5126== at 0x4C2ABB4: calloc (vg_replace_malloc.c:593)
==5126== by 0x400B52: createmat (proj.c:98)
==5126== by 0x401598: main (proj.c:237)
I'd like to figure out out to allocate memory for this, since I'm still a beginner when it comes to memory management in C. Any help would be appreciated, thanks.
EDIT:
The matrix is supposed to store n arrays of strings, which correspond to the lines of the input (it's read with fgets
later), and each array allocates whichever number of words the line has, with each word (read, each string) having at max a MAX_STR
number of characters.
n
is a variable read from the input, while MAX_STR
is a constant defined in the program.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…