green-code-initiative / ecoCode-challenge

Emboard in the hackhatons serie for improving ecoCode
4 stars 5 forks source link

[Hackathon 2024][Neodyme][C] Avoid passing by value #121

Open Dryss10 opened 5 months ago

Dryss10 commented 5 months ago

Rule title

Avoid passing by value.

Language and platform

C

Rule description

Instead of copying strings, arrays, or large structs, consider copying a pointer to them. As long as you're done using the pointer before you modify the string, array, or struct you're okay.

ANSI C now requires that structs are pass-by-value like everything else, thus if you have extraordinarily large structs, or are making millions of function calls on medium-sized ones, you might consider passing the struct's address instead, after modifying the called function so that it doesn't perturb the contents of the struct.

Bad code:

// function which use a copy of the array
static void func(double *arr)
{
    for (int i = 0; i < 100000000; i++) {
        arr[i] += 1;
    }
}
int main(int argc, char *argv[])
{
    // Allocate the memory for the array
    double *arr = malloc(sizeof(double) * 100000000);

    // Initialize the array to 0 
    memset(arr, 0, 100000000);
    // Use of the function
    func(arr);
    free(arr);
    return 0;
}

Good code:

// function which use a copy of the array
static void func(double **arr)
{
    for (int i = 0; i < 100000000; i++) {
        (*arr)[i] += 1;
    }
}

int main(int argc, char *argv[])
{
    // Allocate the memory for the array
    double *arr = malloc(sizeof(double) * 100000000);

    // Initialize the array to 0 
    memset(arr, 0, 100000000);
    // Use of the function
    func(&arr);
    free(arr);
    return 0;
}

Rule short description

Avoid overloading memory unnecessarily.

Rule justification

No concrete documentation. We carried out tests on the code above and found that the difference in performance between the two programs was almost undetectable. We would need to develop tests on the cpu and its consumption, or on the memory used by these two programs.

Bad code:

without_pointer

Good code:

with_pointer

Severity / Remediation Cost

Severity: Minor (depends of size of the data)

Remediation: Easy

Remediation consists in using pointers instead of value.

Implementation principle

In a function prototype check the arguments and if the arguments type are arrays or structs, check that it is passed with a pointer instead of its value.