0gener 0gener - 25 days ago 10
C Question

Allocating the wrong memory

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?

Answer

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)
Comments