Sign in to follow this  
Codorke

strcat problems

Recommended Posts

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

Share this post


Link to post
Share on other sites
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

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this