Tableau multidimensionnel et allocation
Salut,
j'ai écrit une fonction pour faire la chose suivante: je voudrais que ma fonction m'alloue de la mémoire pour un tableau de pointeurs vers des pointeurs de chaînes de caractère de taille n. Voici le code:
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
| char*** _alloc(int n, int m, int r)
{
char*** p;
int i;
int j;
/* Adresse du tableau de pointeurs vers des pointeurs de char* */
p = malloc(sizeof*p);
if (p == NULL)
{
fprintf(stderr,"Allocation impossible\n");
exit(-1);
}
*p = malloc(n*sizeof(char**));
if ( *p == NULL)
{
fprintf(stderr,"Allocation impossible\n");
exit(-1);
}
else
{
for(i=0; i < n; i++)
{
*p[i] = calloc(m,sizeof(char*));
if (*p[i] == NULL)
{
printf("Allocation impossible\n");
exit(-1);
}
}
}
**p = malloc(HASH_SIZE*sizeof(char));
return p;
} |
Dans mon application, je lis un fichier qui est composée de 23 lignes et alloue mon tableau avec le triplet (1,23,taille du hash).
Voici le code de ma fonction main():
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
| int main(void)
{
FILE* datafile;
FILE* fd;
const char* path;
int (*between_hashes)(const char*,const char*,const char*);
path = "/home/jro/doc/diploma/projet/src/data.txt";
char line[BUFSIZ];
char data_hash[HASH_SIZE];
char id[HASH_SIZE];
char*** set_data;
int nline;
between_hashes = between_hashes_sha1;
/*Initialisation des fonctions de manipulation du hash.*/
if (NULL == (datafile = fopen(path,"r")))
{
fprintf(stderr,"Impossible d'ouvrir fichier %s\n",path);
exit(-1);
}
nline = count_line(fd,path);
DEBUGP("_alloc()");
set_data = _alloc(1,nline,HASH_SIZE);
int pos = 0;
while (fgets(line,BUFSIZ,datafile))
{
calculate_hash(line, data_hash, NULL);
strcpy(set_data[0][pos],data_hash);
pos++;
// printf("%s(%s)\n",data_hash,line);
}
int i;
i = between_hashes(set_data[0][0], set_data[0][1], set_data[0][2]);
(i != 1) ? pr("not between") : pr("between");
i = between_hashes(set_data[0][2], set_data[0][1], set_data[0][0]);
(i != 1) ? pr("not between") : pr("between");
if (!feof(datafile))
{
fprintf(stderr,"Erreur de lecture du fichier!!\n");
exit(-1);
}
fclose(datafile);
return 0;
} |
J'ai un signal SIGSEGV à la ligne ou se trouve strcpy(). Je pense que dans mon allocation, il y une erreur. J'ai, en effet, fait un test et j'arrive à copier dans set_data[0][0] et non pas dans set_data[0][1]. Ai-je probablement oublié d'allouer de la mémoire quelque part dans ma fonction _alloc()?
Johnny.