Hobowpen
Hobowpen

Reputation: 71

Unexpectable array allocation in c

I have this code written:

        Resident_x * infos_shorted;
        Residents=6;
        infos_shorted=(Resident_x *)malloc(Residents*(sizeof(Resident_x)));
        i=0;
        while ((infos_shorted+i)!=NULL){
              printf ("%d\n", i);
              i++;
           }

Although someone would expect that I have allocated 6 memory places, when I run it it keeps printing i 's until I terminate it manually.

Thats what I have done to find an answer to my main problem which is this:

I write :

    Resident_x * infos_shorted;
    Residents=6;
    infos_shorted[i].height[8]=7;
    infos_shorted=(Resident_x *)malloc(Residents*(sizeof(Resident_x)));
    for (i=0; i<=Residents+4; i++){
          printf ("%d %d\n", infos_shorted[i].height, i);
    }

And I get the infos_shorted[i].height[8] printed correctly. How is that;

Upvotes: 0

Views: 73

Answers (2)

pm100
pm100

Reputation: 50110

you are expecting C runtime to behave how you would like it to behave; sadly it does not behave that way. malloc allocates you a chunk of memory, it is up to you to know where its start and end are

you must do

  const int NRES = 6;
  Resident_x * infos_shorted;
    Residents=NRES;
    infos_shorted=(Resident_x *)malloc(Residents*(sizeof(Resident_x)));
    i=0;
    for(int i = 0; i < NRES; i++){
       ...info_shorted[i];
       }

Upvotes: 0

Daniel Fischer
Daniel Fischer

Reputation: 183873

while ((infos_shorted+i)!=NULL){

As soon as i > Residents, you have undefined behaviour. Nevertheless, infos_shorted + i will very probably evaluate to an address i*sizeof(Resident_x) bytes behind the value of infos_shorted. There is no reason to expect such an address to be a null pointer (until it wraps, but that is yet more undefined behaviour).

Upvotes: 1

Related Questions