Hi, I have been struggling with Valgrind's error in this function:

void parse_date(char *date_out) {
	char *date_in = __DATE__;
	int month = 0, day = 0;
	char *str_month = (char*) malloc(sizeof(char) * 4);
	char *str_day = (char*) malloc(sizeof(char) * 3);

	/* check mallocs */
	if ((str_day == NULL) || (str_month == NULL)) {
		exit(EXIT_FAILURE);
	}

	strncpy(str_month, date_in, 3);

	if (strcmp(str_month, "Jan") == 0)
		month = 1;
	else if (strcmp(str_month, "Feb") == 0)
		month = 2;
	else if (strcmp(str_month, "Mar") == 0)
		month = 3;
	else if (strcmp(str_month, "Apr") == 0)
		month = 4;
	else if (strcmp(str_month, "May") == 0)
		month = 5;
	else if (strcmp(str_month, "Jun") == 0)
		month = 6;
	else if (strcmp(str_month, "Jul") == 0)
		month = 7;
	else if (strcmp(str_month, "Aug") == 0)
		month = 8;
	else if (strcmp(str_month, "Sep") == 0)
		month = 9;
	else if (strcmp(str_month, "Oct") == 0)
		month = 10;
	else if (strcmp(str_month, "Nov") == 0)
		month = 11;
	else if (strcmp(str_month, "Dec") == 0)
		month = 12;

	/* substring day */
	memset(str_day, '\0', sizeof(char) * 3);
	strncpy(str_day, (date_in + 4), 2);
	day = atoi(str_day);

	if (day < 10) {
		*date_out = '0';
		strcpy(date_out + 1, str_day + 1);
	} else {
		strcpy(date_out, str_day);
	}

	*(date_out + 2) = '-';

	/* substring month */
	memset(str_month, '\0', sizeof(char) * 3);
	//str_month = itoa(month, str_month, 10);
	sprintf(str_month, "%d", month);

	if (month < 10) {
		*(date_out + 3) = '0';
		strcpy(date_out + 4, str_month);

	} else {
		strcpy(date_out + 3, str_month);
	}

	*(date_out + 5) = '-';

	/* add year */
	strcpy(date_out + 6, date_in + 7);

	free(str_month);
	free(str_day);
}

Valgrind's msg is twice:

==8664== Conditional jump or move depends on uninitialised value(s)
==8664==    at 0x4027A08: strcmp (mc_replace_strmem.c:337)
==8664==    by 0x804AC02: parse_date (in /home/lxuser/Plocha/src/xml)

How should I initiate the str_month, I thought that line #12 initiation is sufficient :(

>> How should I initiate the str_month, I thought that line #12 initiation is sufficient

strncpy() does not necessarily NULL-terminate the string -- so, you might do e.g. ..

str_month[3] = '\0';

strncpy() does not necessarily NULL-terminate the string -- so, you might do e.g. ..

str_month[3] = '\0';

I didn't know about this strncpy() feature; Thank you!

This question has already been answered. Start a new discussion instead.