0
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 says invalid write of size 1 at memset ("###" - marked line). Please help figure out what is wrong here. Following "Address 0x0 is not stack'd, nor malloc'd nor free'd" of valgrind output I could rule out strtok as being responsible. It probably is obvious...

alk
  • 69,737
  • 10
  • 105
  • 255

1 Answers1

1

Please help figure out what is wrong here. Following "Address 0x0 is not stack'd, nor malloc'd nor free'd"

Well, the address came from malloc, and malloc could fail. When it does fail, it returns NULL, which explains the 0x0 address.

The reason malloc fails is likely that you are leaking memory elsewhere.

Employed Russian
  • 199,314
  • 34
  • 295
  • 362