strcat problems

Started by
2 comments, last by Codorke 18 years, 8 months ago
Could someone tell me whats wrong ? int num_pages = get_total_text_pages(); char buffer[5]; for(int i=0; i<MAX_PAGES; i++) { // Marked Pages if(i<=num_pages) { string_before = "<page nr='"; _itoa(i+1, buffer, 10); strcat(string_before, buffer); strcat(string_before, "' marked='"); if(StrToInt(find_in_text(S, string_before, '\'')) == 1) set_marked_pages(i, true); else set_marked_pages(i, false); }else set_marked_pages(i+1, false); } Thanks in advance
Advertisement
The problem is
string_before = "<page nr='";
string_before is pointing to a constant string. You'd want a strcpy here.
_______________The essence of balance is detachment. To embrace a cause, to grow fond or spiteful, is to lose one''s balance after which, no action can be trusted. Our burden is not for the dependent of spirit. - Mayar, Third Keeper
To expand on that slightly, string_before is a pointer to a character. The expression string_before = "<page nr="; makes string_before point to the first character of the constant string "<page nr=", which will probably be stored in the programs data segment. The function strcat appends it's second argument to the end of it's first argument. It requires that it's first argument has sufficient allocated memory to contain both strings. In your case you don't. You're not even allowed to write into the data segment. Instead you should do something like one of the following:
Pure C:
int num_pages = get_total_text_pages();int required_size;char * string_before;for (int i = 0; i < MAX_PAGES; ++i){	if (i < num_pages)	{		required_size = snprintf(0, 0, "<page nr='%i' marked='", i + 1);		if (required_size > 0)		{			string_before = (char *)malloc(required_size + 1);			if (!string_before || snprintf(string_before, required_size + 1, "<page nr=%i marked='", i + 1) != required_size)			{				// error			}		}		else		{			// error		}		// the rest of your code		free(string_before);	}}


C++:
int num_pages = get_total_text_pages();for (int i = 0; i < MAX_PAGES; ++i){	std::string string_before = "<page nr='" + boost::lexical_cast< std::string >(i + 1) + "' marked='";	// rest of your code, possibly using string_before.c_str() if interfacing with C code.}

Enigma
Thanks fort helping me out !
This works indeed.

This topic is closed to new replies.

Advertisement