Regex code example without "uninitialized" warnings?

dg9ngf
Posts: 17
Joined: Mon Sep 16, 2019 6:49 pm

Regex code example without "uninitialized" warnings?

Postby dg9ngf » Sun Jan 16, 2022 9:08 pm

I'm trying to parse an MQTT topic that may contain variables. Regex seems like the easiest solution here. But the C API of regex seems like a PITA. I followed the manpage and examples from the web, but the compiler rejects it.

Code: Select all

regex_t ledRegex;
regcomp(&ledRegex, "^/led/ch/([0-9]+)/([a-z]+)", 0);

regmatch_t match[3];
if (regexec(&ledRegex, topic, 2, NULL, 0) == 0)
{
	char* p1 = strndup(event->topic + match[1].rm_so, match[1].rm_eo - match[1].rm_so);
	char* p2 = strndup(event->topic + match[2].rm_so, match[2].rm_eo - match[2].rm_so);
	printf("LED topic parsed: ch=%s cmd=%s\n", p1, p2);
	//uint16_t num = strtol(data, NULL, 10);
	free(p1);
	free(p2);
}
This is the error:
error: 'match[1].rm_so' may be used uninitialized in this function [-Werror=maybe-uninitialized]
It's repeated for every access of that structure.

Should I stop regarding compiler warnings? In the past 15 years of coding in C# I managed to resolve all warnings, many of them pointed me to real problems and needed fixing. Not sure how C handles this.

I'm using VSCode and the esp-idf extension.

dg9ngf
Posts: 17
Joined: Mon Sep 16, 2019 6:49 pm

Re: Regex code example without "uninitialized" warnings?

Postby dg9ngf » Sun Jan 16, 2022 9:26 pm

More trouble.

For an ugly quick fix, I added this to convince the compiler that it's okay:

Code: Select all

match[1].rm_so = 0;
match[1].rm_eo = 0;
match[2].rm_so = 0;
match[2].rm_eo = 0;
But the code doesn't match the input "/led/ch/0/temp". The return value is REG_NOMATCH. regcomp() returned 0 which is good.

If I pass the REG_EXTENDED flag to regcomp, it still returns 0 but regexec crashes the application and reboots.

Should I roll my own string parsing instead of fighting the regex functions that the code editor doesn't even know? This line is underlined:

Code: Select all

#include <regex.h>
with the message: The include file was not found in "browse.path" (message translated by me)

WiFive
Posts: 3510
Joined: Tue Dec 01, 2015 7:35 am

Re: Regex code example without "uninitialized" warnings?

Postby WiFive » Sun Jan 16, 2022 10:18 pm

Try "^/led/ch/\\([0-9]\\+\\)/\\([a-z]\\+\\)"

dg9ngf
Posts: 17
Joined: Mon Sep 16, 2019 6:49 pm

Re: Regex code example without "uninitialized" warnings?

Postby dg9ngf » Mon Jan 17, 2022 9:48 am

WiFive wrote:
Sun Jan 16, 2022 10:18 pm
Try "^/led/ch/\\([0-9]\\+\\)/\\([a-z]\\+\\)"
Are you sure what that means? I don't want to escape the control characters, I want them to work. There are no parentheses and plus signs in my data to match.

Who is online

Users browsing this forum: Baidu [Spider] and 38 guests