Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

strcat and memory-allocation

Status
Not open for further replies.

DoraC

Programmer
May 7, 2002
98
US
Hi,

I need to use strcat() to concatenate two strings, call them sFirst and sSecond. sFirst is allocated as follows:
Code:
char* sFirst = (char*)malloc( sizeof(char) );

sSecond is allocated in the same way. I concatenate them
as:
Code:
sFirst = strcat( sFirst, sSecond );

Now, the literature I've read says that strcat will contatenate sSecond to the end of sFirst, returning then sFirst. My question is - what happens if there isn't enough contiguous memory to append sSecond in its entirety to the end of sFirst? Is another char* allocated, assigned-to, and returned? And - if so - does it automatically free the original sFirst memory?

Thank you!
dora c
 
It is your responsibility to ensure enough room for your strings ! Nothing automagically happens behind the scene.

If you fail your program will behave strange ...

> char* sFirst = (char*)malloc( sizeof(char) );
This statement will only allocate 1 char ... and is 'useless' when dealing with strings.

/JOlesen
 
char *strcat( char *strDestination, const char *strSource );

[The strcat function appends strSource to strDestination and terminates the resulting string with a null character. The initial character of strSource overwrites the terminating null character of strDestination. No overflow checking is performed when strings are copied or appended. The behavior of strcat is undefined if the source and destination strings overlap.]

1. As Jolesen said is your responsability to ensure (allocate) ENOUGH memory for the strDestination in order to append the strSource or to check that the strDestination and strSource strings do not overlap.
If you don't do that the results are undefined.
What means that ?
The strDestination has to have enough room to receive the entire strSource INCLUDING the null terminating character.
2. There is no automatically free of the memory for any allocation call. In other languages yes but not in C.

3. The strncat() function is another way to concatenate strings.

-obislavu-
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top