Frying a String

The challenge for September’s Exercise is to scramble a string, jumbling its characters in a random pattern. I figured it’s a fun exercise, not anything useless beyond curiosity. Yet such a function exists for the GNU C library, strfry().

The strfry() function isn’t part of the standard C library. In fact, you must contort your code a bit to rummage through the GNU C library to access it. Such digital gymnastics means that only certain environments have access to the GNU C library. In my cursory examination of the strfry() function, I’ve discovered that it’s available primarily in Linux.

To quickly check for the strfry() function’s availability, use the command man strfry in a terminal window. If no entry is found, bummer. Otherwise, you see this format:

char *strfry(char *string);

Unlike my scramble() function which modified the original string, the strfry() function returns a freshly scrambled string, leaving the original string as-is. The function requires the string.h header file — but more importantly, it requires the _GNU_SOURCE defined constant declared at the tippy-top of the source code file:

#define _GNU_SOURCE

It’s this directive that activates the GNU C library functions, making them available where otherwise they lie dormant. This #define is known as a feature test macro. It exposes certain functions in header files, which means this preprocessor directive must be declared first, at the tippy-top of the source code file:

2021_10_02-Lesson.c

#define _GNU_SOURCE
#include <stdio.h>
#include <string.h>


int main()
{
    char s[] = "Hello there, handsome devil!";

    printf("Before: %s\n",s);
    printf("After: %s\n",strfry(s));

    return(0);
}

Line 1 is the _GNU_SOURCE feature test macro. It exposes the custom GNU library functions in the stdio.h and string.h header files. Specifically, it rouses the strfry() function in the printf() statement at Line 11. This function’s return value is immediately swallowed by the printf() function’s %s placeholder, outputting the scrambled string:

Before: Hello there, handsome devil!
After: ll emete ,dheno!vH aidsoerhl

I’m unaware of the function’s internals, whether it uses the randomized method I chose for my solution to last month’s Exercise or whether it uses the character-swap method demonstrated by Chris Webb. My guess is that it uses the character-swap method.

Obviously, strfry() is an oddball function. I suppose it could end up in other libraries, though I don’t see why. While it’s fun and interesting, the desire to scramble a string doesn’t seem to be high on any programmer’s priority list. And, as always, if you need a function that’s not in any library, you can always code it yourself.

Leave a Reply