0gener 0gener - 1 year ago 80
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);

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;


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 Source

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)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download