The following program compiles with no errors. If left as is, it will execute with no apparent errors.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#define ARGCNT 5
void show_array(const double * array, int num);
double * new_d_array(int num, ...);
int main(void)
{
double * p1;
p1 = (double *) malloc(ARGCNT * sizeof(double));
p1 = new_d_array(ARGCNT, 1.2, 2.3, 3.4, 4.5, 5.6);
show_array(p1, ARGCNT);
free(p1);
puts("Goodbye!");
return 0;
}
void show_array(const double * array, int num)
{
int ct;
for (ct = 0; ct < num; ct++)
printf("%.2lf ", array[ct]);
putchar('\n');
}
double * new_d_array(int num, ...)
{
int ct;
double * array;
va_list holder;
va_start(holder, num);
for (ct = 0; ct < num; ct++)
array[ct] = va_arg(holder, double); // crashes HERE
va_end(holder);
return &array[0];
}
The behavior I don't understand is: when I change the line
Code:
p1 = new_d_array(ARGCNT, 1.2, 2.3, 3.4, 4.5, 5.6);
to include more (or fewer) arguments, the program crashes at the commented spot. I am of course changing the body of ARGCNT to reflect the addition (or subtraction) of double values. It doesn't seem to matter.
To make this even more interesting, if I leave the five double values as they are, but change the ARGCNT body to any number above or below 5, it will still run fine, but will truncate or add on output as expected. The added output (above 5 arguments) will be zeroed out double values, but it will still process and print them.
Where is the problem???