0
int* readFile(char* name){
FILE* file = fopen (name, "r");

if(file == NULL)
{
    printf("Failed to open the file %s\n", name);
    exit(1);
}

int* a = (int*) malloc(sizeof(int) * NUM_CONFIGS);
int num, i = 0;
printf("TEST1: %d\n", sizeof(a));
/* line format:  CONFIG_NAME=5 */
char config_name[25];
char line[28];

while(fgets(line, sizeof(line), file)){
    sscanf(line, "%[^=]=%d", config_name, &num);
    a[i] = num;
    i++;
}

fclose(file);

return a;
}

The NUM_CONFIGS is currently 3, and the result of the printf is TEST1: 8, where it should be 12. If i change the NUM_CONFIGS to 30 the result is again TEST1: 8. What's the problem here? Then if I go and print the array values it prints this:[25,10] and it should be [25,10,3]. And how to I free the allocated space in this case?

0gener
  • 135
  • 10
  • 1
    "...where it should be 12"? Where did you get that idea? Your `sizeof` evaluates to the size of pointer type on your platform, which is 8. Exactly as it should be. Also, don't attempt to print the result of `sizeof` with `%d`. `%d` is for `int`. `sizeof` returns `size_t`, which is not `int`. – AnT stands with Russia Nov 07 '16 at 07:39
  • 2
    Side note: `sizeof(a)` is the size of a pointer (typically 4 or 8 bytes, depending on your platform), not the size of the allocated memory block which `a` is pointing to. – barak manos Nov 07 '16 at 07:40
  • Possible duplicate of [newbie questions about malloc and sizeof](http://stackoverflow.com/questions/1533519/newbie-questions-about-malloc-and-sizeof) –  Nov 07 '16 at 07:42
  • You can't `sizeof` the `malloc`ated array of bytes. You'll just have to remember the size somewhere. –  Nov 07 '16 at 07:43
  • Do *NOT* cast the return of `malloc`, it is unnecessary. See: [**Do I cast the result of malloc?**](http://stackoverflow.com/q/605845/995714) for thorough explanation. Also, the `*` goes with the *variable*, NOT the *type*, (e.g. `int *a;`, which prevents confusion like `int* a, b, c;` -- `b` and `c` are not `int*`) – David C. Rankin Nov 07 '16 at 07:48

1 Answers1

1

With int* a = ...:

  • sizeof(a) is not the size of the allocated memory block which a is pointing to
  • sizeof(a) is the size of a pointer (typically 4 or 8 bytes, depending on your platform)

With int a[NUM_CONFIGS]:

  • sizeof(a) is the size of the array (i.e., sizeof(int) * NUM_CONFIGS)
  • sizeof(a)/sizeof(*a) is the number of entries in the array (i.e., NUM_CONFIGS)
barak manos
  • 29,648
  • 10
  • 62
  • 114
  • 1
    So in this case I should define a[NUM_CONFIGS] instead of int* a? – 0gener Nov 07 '16 at 07:48
  • @0gener: That depends on your purpose. Usually, the choice between static allocation and dynamic allocation is not based on the ultimate purpose of printing the size of the allocated object. If that is your goal, then I suppose that you may as well allocate it statically (though you could just as well print `sizeof(int) * NUM_CONFIGS`). – barak manos Nov 07 '16 at 07:50