Given the following script:
%typemap(in,noblock=1) int * {
$1 = malloc(sizeof(int));
if($1 == NULL) {
return $null;
}
}
%typemap(freearg,noblock=1) int * {
free($1);
}
void afunc(int *varA, int *varB);
For Java, SWIG generates:
SWIGEXPORT void JNICALL Java_testmoduleJNI_afunc(JNIEnv *jenv, jclass jcls, jlong jarg1, jlong jarg2) {
int *arg1 = (int *) 0 ;
int *arg2 = (int *) 0 ;
(void)jenv;
(void)jcls;
arg1 = malloc(sizeof(int));
if(arg1 == NULL) {
return ;
}
arg2 = malloc(sizeof(int));
if(arg2 == NULL) {
return ;
}
afunc(arg1,arg2);
free(arg1);
free(arg2);
}
If arg2
fails to allocate successfully, this would leak the memory allocated for arg1
. Python and other languages have SWIG_fail, but this doesn't exist for Java. Is there any way to avoid this?