8
\$\begingroup\$

According to this consensus in the default allowed inputs thread, functions may output by writing to an out argument.

When outputting an array in languages like C/C++, where arrays are pointers to locations in memory, can we assume the memory at the output location to have been allocated and to be of a sufficient size to output the complete answer, or must the memory be allocated in the code?

Below are some example functions in C that output by modifying their parameters; please consider each case, and state which cases you'd consider acceptable.

// Fixed size
void one_to_ten(int*o){
    for(int i=1; i<=10; i++)
        o[i-1]=i;
}

// Output size is a function of input size
void mul_table(int*o,int*a,int m,int*b,int n){
    for(int i=0; i<m; i++)
        for(int j=0; j<n; j++)
            o[i*n+j]=a[i]*b[j];
 }

// Size of output is given
void roll_dice(int*res, int n){
    for(int i=0; i<n; i++)
        res[n]=rand()%6+1;
}

// Output has a variable size and a defined maximum size
void scramble(int*o, int seed){
    srand(seed);
    int r;
    for(int i=0; (r=rand())&&i<128; i++)
        o[i]=r;
}
\$\endgroup\$
2
  • \$\begingroup\$ The range of where should be defined the arg is 0..9 so the array in the arg would be int a[n]; with n>=10 \$\endgroup\$
    – user58988
    Dec 20, 2018 at 15:15
  • \$\begingroup\$ @RosLuP I'm not sure if I understand what you are saying. \$\endgroup\$
    – user77406
    Dec 20, 2018 at 20:27

1 Answer 1

2
\$\begingroup\$

You can at least assume the output buffer is enough

Anyway even GCC doesn't(or can't) check it when doing memcpy

\$\endgroup\$
1
  • \$\begingroup\$ Strictly speaking, GCC never does memcpy in a way you're talking about: it just inserts call to library or syscall. \$\endgroup\$ Jun 25, 2019 at 12:15

You must log in to answer this question.