void readdat (int c, char **v) {
char *dc;
char *pdc;
dc = malloc((line+1) * sizeof(char));
memset(dc, 0, (line+1) * sizeof(char));
FILE *datfile;
datfile = fopen(v[3], "r");
while(fgets(dc, line, datfile) != NULL) {
pdc = strtok(dc, "\t");
countcDat = 0;
while(pdc != NULL) {
++countcDat;
pdc = strtok(NULL, "\t");
}
++countrDat;
}
dat = malloc(countrDat * sizeof(char**));
memset(dat, 0, countrDat * sizeof(char**));
for(i=0;i<countrDat;++i) {
dat[i] = malloc(countcDat * sizeof(char*));
memset(dat[i], 0, countcDat * sizeof(char*));
}
for(i=0;i<countrDat;++i) {
for(j=0;j<countcDat;++j) {
dat[i][j] = malloc(20 * sizeof(char));
memset(dat[i][j], 0, 20 * sizeof(char)); ###
}
}
rewind(datfile);
countrDat = 0;
countcDat = 0;
while(fgets(dc, line, datfile) != NULL) {
pdc = strtok(dc, "\t");
countcDat = 0;
while(pdc != NULL) {
sscanf(pdc, "%s", dat[countrDat][countcDat]);
++countcDat;
pdc = strtok(NULL, "\t");
}
++countrDat;
}
for(i=0;i<countrDat;++i) {
for(j=0;j<countcDat;++j) {
printf("%s\t", dat[i][j]);
}
printf("\n");
}
fclose(datfile);
free(dc);
for(i=0;i<countrDat;++i) {
for(j=0;j<countcDat;++j) {
free(dat[i][j]);
}
}
for(i=0;i<countrDat;++i) {
free(dat[i]);
}
free(dat);
}
valgrind 表示 memset 处的大小为 1 的写入无效(“###” - 标记行)。请帮忙找出这里出了什么问题。在 valgrind 输出的“地址 0x0 未堆叠、未分配或释放”之后,我可以排除 strtok 的责任。这可能是显而易见的......
最佳答案
Please help figure out what is wrong here. Following "Address 0x0 is not stack'd, nor malloc'd nor free'd"
嗯,地址来自 malloc
,并且 malloc
可能会失败。当它失败时,它返回NULL
,这解释了0x0
地址。
malloc
失败的原因很可能是您在其他地方泄漏了内存。
关于c - 无效写入大小 : memset,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15151093/