Steven said:
The following program runs alright until the return statement, where it
crashes, and consequently, Dr. Watson (drwtsn32.exe) also crashes.
Deleting the call to fgets() and everything runs fine. I *think* the
stack or something got mess up during the fgets(). Could anyone help?
Thanks.
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]){
char **fbuffer=(char **)malloc(8192*sizeof(char));
FILE *fp=fopen("data.dat","r");
fgets(fbuffer[count],64,fp); //Trouble here.
printf("%s",fbuffer[count]);
system("pause");
return 0;
}
//(data.dat contains 2 short lines of text)
You've allocated memory for 8192 pointers-to-char. Or you have
attempted to; you haven't checked that the return from malloc()
was not NULL. That could be a problem in production code, but
it's not the real issue here. Likewise with the fact that you've
added a redundant cast "(char **)" to the return from malloc,
which, as a void *pointer is already ready for action in any
capacity.
The most important problems with the code are two-fold.
1) Those little double asterisks ("**") mean that you're
dealing with a pointer-to-pointer-to-char. I presume you
intend to allocate 8192 pointers-to-char, but in that case
the size you have given to malloc is wrong. In the C language
sizeof(char) is, by definition, 1. But the size of a pointer
to char is not 1 by definition, and in practical contexts is
almost sure to be greater than 1.
You should say:
char **fbuffer = malloc(8192 * sizeof *fbuffer);
(or, "give me 8192 of whatever fbuffer points to, please").
2) Even supposing you'd succeeded in allocating 8192 pointers
to char, each and every one of them is pointing nowhere, and is
not ready to receive any char data. If you want to use the
fgets() construction you have shown, then you have to first
point each of your pointers-to-char to a 64-byte arena, with
something like
int i;
for (i=0; i<8192; i++) {
fbuffer
= malloc(64);
}
3) There's also the small matter of count's being undeclared.
I presume it is an int, initialized to 0 and incremented
after each call to fgets().
Or just maybe you don't really want 8192 pointers-to-char after
all. In that case, lose the "**".
FILE *fp;
char *buf;
fp = fopen("data.dat","r"); /* check return */
buf = malloc(64); /* check return */
fgets(buf, 64, fp);
printf("%s", buf);
Allin Cottrell