aseed
aseed

Reputation: 120

can anyone explain the differences between the two allocs and why bad and good?

can anyone explain the differences between the two allocs and why bad and good? what happen in each case of bad and good?

bad alloc

  void get_memory(char *arr, int length){
        if((arr=(char*)malloc(length * sizeof(char))) == NULL)
        {
            puts("Not enough memory. Sorry.\n");
            exit(-1);
        }
    }
    void main(void){
        char *str = NULL;
        get_memory(str, 128);
        strcpy(str,"Program illegally runs over memory !\n");
        puts(str);
        free(str);
    }

good alloc

void get_memory(char **arr, int length){
    if( (*arr = (char*)malloc(length * sizeof(char))) ==
        NULL)
    {
        puts("Not enough memory. Sorry.\n");
        exit(-1);
    }
}
void main(void){
    char *str = NULL;
    get_memory(&str, 128);
    strcpy(str, "This program works fine !\n");
    puts(str);
    free(str);
}

Upvotes: 0

Views: 55

Answers (3)

Valeri Atamaniouk
Valeri Atamaniouk

Reputation: 5163

As others have already answered your question, I add an alternative:

void get_memory(char **arr, size_t length){
   if((*arr = malloc(length)) == NULL && 0 != length)
   {
       puts("Not enough memory. Sorry.\n");
       exit(-1);
   }
}

Reasoning: length shall not be negative. And when it is 0, the result of malloc can be NULL.

malloc returns void*, which is automatically casted to an appropriate pointer type in C.

As per later C standard, sizeof(char) is 1.

Upvotes: 0

Giuseppe Guerrini
Giuseppe Guerrini

Reputation: 4438

In the "bad" example you are actually throwing away malloc's result, since "str" parameter is passe dby value and will mantain its NULL value after the call. In the second case the function receives a POINTER TO "str", so it's able to manipulate "str" and leave the correct value in it.

Upvotes: 0

Eugene Sh.
Eugene Sh.

Reputation: 18371

The bad is that in the first case the pointer arr is passed by value, it's value is modified in the function, and when returning the value is "forgotten". In the second code the reference to the pointer is passed, so the assigned value is retained when out of the function.

Upvotes: 3

Related Questions