1
\$\begingroup\$

Very useful operation that hasn't been merged into a function.. until now. This is supposed to insert a substring into a previously d.allocated source string.

void strapp (char *source_offset, int position, char *appendage)
{
 size_t appendage_size = strlen(appendage) + 1;
 char copy[strlen(source_offset)];
 strcpy(copy, source_offset);
 source_offset = realloc(source_offset, strlen(source_offset) + appendage_size);
 memcpy(&source_offset[position], appendage, strlen(appendage));
 sprintf(source_offset + (position + strlen(appendage)), &copy[position]);
}

USAGE:

int main(void)
{
 char *str1 = malloc(11 + 1);
 sprintf(str1, "Hello World");
 strapp(str1, 5, " Horrible");
 printf(str1);
 free(str1);
 return 0;
}

Produces the output:

Hello Horrible World

asked Feb 2, 2015 at 7:30
\$\endgroup\$
0

2 Answers 2

3
\$\begingroup\$

This is more of a string-inserting function than a string-appending function, and should be renamed as such.

When calling realloc(...), the string could very well move to a different memory location. The caller of strapp() has no way of knowing where the new string is, though. Furthermore, if the string got moved, and the caller continues to use the string as if were still at source_offset, then that's a memory-use-after-free bug.

There are two possible remedies:

/**
 * s points to the address of the old and new string.
 */
string_insert(char **s, int insertion_pt, const char *to_insert)

or

/**
 * Returns the location of the new string, which may or may not be at
 * the original s. Callers must assume that the string at s may be
 * invalid after this call.
 */
char *string_insert(char *s, int insertion_pt, const char *to_insert)
answered Feb 2, 2015 at 8:20
\$\endgroup\$
1
\$\begingroup\$
 sprintf(source_offset + (position + strlen(appendage)), &copy[position]);

may produce an undefined behavior if a trailing part of the source string has embedded % characters. Either use an explicit format string

 sprintf(source_offset + (position + strlen(appendage)), "%s", &copy[position]);

or memcpy it.

answered Feb 2, 2015 at 18:37
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.