-3

Write a program to ask the user to enter the total number of float data. Then use the calloc() and malloc() functions to allocate two memory blocks with the same size specified by the number, and print out the initial values of the two mem- ory blocks.

My solution is:

float *p_1,*p_2;
int i,num_of_floats=0;
printf("the total number of float numbers: ");
scanf("%d",&num_of_floats);
if((p_1=calloc(num_of_floats,sizeof(float)))==NULL||(p_2=malloc(num_of_floats*sizeof(float)))==NULL){
  printf("error at alllocating!!\n");
  exit(1);
}
else{
  for(i=0; i<num_of_floats ;i++){
    printf("%f",*(p_1+i));
  }
  printf("\n");
  for(i=0; i<num_of_floats ;i++){
    printf("%f",*(p_2+i));
  }
}
free(p_1);
free(p_2);

return 0;

output:

the total number of float numbers: 5
0.0000000.0000000.0000000.0000000.000000
0.0000000.0000000.0000000.0000000.000000

The malloc function doesn't Initialize the values to zero, and still i get zeros.

Mor Haham
  • 65
  • 7

1 Answers1

1

If you do not initialize your values, you can get any data. Zeroes are a valid kind of "any data".

You're more likely to see it in debug builds, wherein some the C++ runtimes zero out a good portion of its heap memory at program startup in order to make it easier for you to see when you're using it. Although, in my opinion, it makes it less clear that you're failing to initialize your data, as shown by this very question.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055