g_list_find always returns NULL when using user-provided input
GLib version: 2.68.4, 2.70.2
Operating System: Ubuntu Server 21.10 x86_64, Fedora Workstation 35 x86_64
How to reproduce:
- Compile main.c using the usual GCC command (
gcc main.c -o main $(pkg-config --libs --cflags glib-2.0)
)
/* main.c */
// MIT/X11/Expat License
#include <stdio.h>
#include <glib-2.0/glib.h>
static void GList_PrintContents(GList *list){
printf("List contents (pick one):\n");
for(int _ = 0; _ < g_list_length(list); _++){
printf("\t%s\n", (char *) g_list_nth_data(list, _));
}
}
static void GList_PrintMatch(GList *list, const char *match){
printf("%s == %s\n", (char *) g_list_nth_data(g_list_find(list, match), 0), match);
}
int main(int argc, const char *argv[]){
const char *array[] = {"lorem",
"ipsum",
"dolor",
"sit",
"amet"};
GList *list = NULL;
for(int _ = 0; _ < 5; _++){
list = g_list_prepend(list, (gpointer) array[_]);
}
list = g_list_reverse(list);
if(argc < 2){
GList_PrintContents(list);
const char *match = "lorem";
printf("Example:\n\t%s == %s\n", (char *) g_list_nth_data(g_list_find(list, match), 0), match);
} else {
printf("Compile-time constant -- works just fine:\n\t");
const char *match = "lorem";
GList_PrintMatch(list, match);
printf("User-provided input -- does not work:\n\t");
const char *match0 = argv[1];
GList_PrintMatch(list, match0);
}
return 0;
}
- Run the resulting binary (
./main
)
- Run the resulting binary with a list entry of your choice, for example "lorem" (
./main lorem
)
Expected outcome: It should be showing the matched list entry, which is possible if g_list_find
is called with a compile-time constant, evident in the example code given.
The issue also applies when g_list_find
is used inside a library call, exhibiting the same behavior.
I tried looking over glib/glist.c
but I have no idea on how it wouldn't work.
Edited by rmnscnce