I've a problem with array[global] values getting lost in function call.
Here is the flow.
===========driver.c=================
/* this is just a driver to test a library wrapper
* originally it's a cobol program calling a c library function
*/
# include "il_entry.h" /* # define s SCANFUN as il_lib_entry */
int
main(void)
{
int SLEN = 8192;
char SIGNAT[SLEN];
char ISTAT[2]={'0', '0'};
char FNAME[32] = {'0'};
SCANFUN(ILREADIMAGE, FNAME, SIGNAT, "8192", ISTAT);
return 0;
}
=============== il_lib_entry.c =================================
# include <stdarg.h>
# include <stdlib.h>
# define NARGS 10 /* keeps track of memory allocated
*/
char **calargv;
int calargc;
void il_cob(void);
void
il_lib_entry(char *foo, ...)
{
int i=0, n=0;
va_list argv;
char *v;
if (foo != NULL)
{
n = NARGS;
/* start with 10 ptrs first */
if ((calargv = malloc (NARGS * sizeof(char*))) == NULL)
{
perror("malloc");
exit(EXIT_FAILURE);
}
va_start(argv, *foo);
printf("%s\n", foo);
if((calargv[0] = malloc (strlen(foo)+1)) == NULL)
{
perror("malloc");
exit(EXIT_FAILURE);
}
strcpy(calargv[0], foo);
for (i=1; (v=va_arg(argv, char*)) != NULL; i++)
{
/* if (i n)
{
n += NARGS;
calargv = realloc(calargv, n * sizeof(char*));
}
*/
if((calargv[i] = malloc(strlen(v)+1)) == NULL)
{
perror("malloc");
exit(EXIT_FAILURE);
}
strcpy(calargv[i], v);
}
/* if (i n)
{
n++;
calargv = realloc(calargv, n * sizeof(char*));
}
*/
calargv[i] = NULL; /* terminate the
array */
va_end(argv);
calargc = i;
il_cobol(); /* join the old route */
for (i=0; calargv[i]; i++)
free(calargv[i]);
free(calargv);
}
}
==================== library code =================
#include <stdio.h>
#include <fcntl.h>
#include "il_lib.h"
#include "il_cob_lib.h"
extern char *calargv[] ;
extern int calargc ;
static int iretval;
#define NFUN sizeof(il_cob_call)/sizeof(int *)
il_cobol()
{
if (calargc 0) {
int ifun = atoi(calargv[0]);
iretval = 0;
if(ifun < NFUN)
(*il_cob_call[ifun])();
}
return;
}
<snip>
===================== code end ========================
When control enters the library code, the contents of calargv[] are
already corrupt. (Though calargc is correct). Appears that values of
calargv[0] to [4] are changing somewhere after il_lib_entry calls
il_cobol. Can't understand why.
Should calargv be declared as const in il_lib_entry? but I'm confused
as to what should be const in the declaration.
il_lib_entry is the wrapper to the library which alredy existing, so
any change in library code is ruled out, but il_lib_entry() can be
changed to suit.
help appreciated.
~yogesh