0

if

fp_len = ftell(fp); 

prints 470

shouldn't this be printing "471" ? ( it prints 8. probably first line only )

char *text = malloc(sizeof(*text) * fp_len + 1);
int text_len;
text_len = sizeof(text);

printf("text-len: %d --- ",text_len);

full:

FILE *fp;
fp = fopen(path, "r");

fseek(fp, 0, SEEK_END);

int fp_len;
fp_len = ftell(fp); 
printf("%d---", fp_len);

fseek(fp, 0, SEEK_SET);

char *text = malloc(sizeof(*text) * fp_len + 1);

int text_len;
text_len = sizeof(text);
printf("text-len: %d --- ",text_len);

fread(text, fp_len, 1, fp);

printf("%s",text);

free(text);

2 Answers2

1

sizeof gives the size of the type, not a string length. In case of char *text, the type is a pointer value, and the size of a pointer value on a 64 bit machine is probably 8.

Stephan Lechner
  • 34,891
  • 4
  • 35
  • 58
0

The sizeof is an operator in C and not a function. It acts on the type of the expression inside the brackets.

It tells the size of the type. In general cases when you do sizeof of say a char array like,

char array[] = "Hello";
sizeof(array);

you get 6, because the type of array is char[6].

Now in this case you are doing sizeof on text.

text is defined as char* which is a pointer. Pointers on your system are 8 bytes. So it is giving out 8.

Trying to use sizeof which dynamically allocated buffers is not going to work. Instead you can use

sizeof(*text) * fp_len + 1

Because that is what you passed to malloc. That is ACTUALLY the size of the buffer pointed to by text.

Ajay Brahmakshatriya
  • 8,993
  • 3
  • 26
  • 49