Skip to content

Instantly share code, notes, and snippets.

@gmarkall
Created October 10, 2012 10:19
Show Gist options
  • Save gmarkall/3864582 to your computer and use it in GitHub Desktop.
Save gmarkall/3864582 to your computer and use it in GitHub Desktop.
Failure to use PetscFListGet for listing available KSP types
#include <petscsys.h>
#include <petscksp.h>
// Struct copied from reg.c so we can access the members of a PetscFList
struct _n_PetscFList {
void (*routine)(void); /* the routine */
char *path; /* path of link library containing routine */
char *name; /* string to identify routine */
char *rname; /* routine name in dynamic library */
PetscFList next; /* next pointer */
PetscFList next_list; /* used to maintain list of all lists for freeing */
};
int main(int argc,char **argv)
{
PetscErrorCode ierr;
KSP ksp;
ierr = PetscInitialize(&argc,&argv,PETSC_NULL,PETSC_NULL);CHKERRQ(ierr);
// Create a KSP context so that KSPList is initialised
KSPCreate(PETSC_COMM_WORLD,&ksp);
PetscFList list = KSPList;
int count = 0;
// Manually iterate over the KSPList (inspired by the code in PetscFListGet)
// Works OK
while (list) {
printf("%d: %s\n", count, list->name);
list = list->next;
count++;
}
// Get the array of names with PetscFlistGet. Segfaults in PetscTrMalloc...
char ***array;
int *n;
ierr = PetscFListGet(KSPList, array, n);
// Print the array (should be the same as before)
for (int i=0; i<*n; ++i)
printf("%s\n", *array[i]);
ierr = PetscFinalize();
return ierr;
}
@wence-
Copy link

wence- commented Oct 10, 2012

You want:

#include <petscsys.h>
#include <petscksp.h>

int main(int argc,char **argv)
{
  PetscErrorCode ierr;
  KSP ksp;

  ierr = PetscInitialize(&argc,&argv,PETSC_NULL,PETSC_NULL);CHKERRQ(ierr);
  // Create a KSP context so that KSPList is initialised
  KSPCreate(PETSC_COMM_WORLD,&ksp);
  KSPDestroy(ksp);
  PetscFList list = KSPList;

  char **array;
  int n;
  ierr = PetscFListGet(KSPList, &array, &n);

  /* Last entry in array is NULL (this is non-obvious) */
  int i;
  for ( i = 0; *array; i++ ) {
      printf("%d: %s\n", i, *(array++));
  }

  array -= i;
  PetscFree(array);
  ierr = PetscFinalize();
  return ierr;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment