questions about library functions

Programming, for all ages and all languages.
Post Reply
elias

questions about library functions

Post by elias »

im using two library functions for working on strings. memcpy, and memcmp.

now, does memcpy put 0's, or some uniform value in the unused spaces of the array? ie. if you have a 15 char arry, wiht only the first 6 slots being filled be legit chars, and you copy it into another 15 char arry, will the last 9 chars in the array be filled wiht a uniform value? the reason im asking is that when i use memcmp on a string to see if it matches with another, if memcpy dosnt put a uniform value in each unused slot, then it will be filled with junk, and memcpy wont work right, even though they have teh same string. if im being unclear about my question please tell me.
ark

Re:questions about library functions

Post by ark »

memcpy doesn't mess with any memory other than the actual bytes it's copying and the bytes it's writing to, which will be the same number of bytes that were copied.

If str1 (a 14-element char array) contains this:

Hi_there\0?????

and you memcpy 9 bytes to another 14-element array named str2, then you will have

Hi_there\0?????

as str2's value, where the question marks can be any character at all.

Is there some reason why you would use memcpy and memcmp instead of strcpy and strcmp? The str functions are already prepared to properly handle the null characters at the end of a string. Using memcpy with strings is dangerous unless you know what you are doing. If you memcpy only 8 characters from the str mentioned above to str2, then str2's value is:

Hi_there?????? (no null-terminator!!)

If you printf str, you'll get:

Hi_there

but if you printf str2, you might get "Hi_there", but you might also get

Hi_therefsalkfhasdlkfjh^*^%&54

or even worse results. But if you strcpy str to str2 and both str and str2 are 14-element arrays, then you know that strcmp(str, str2) will return 0, indicating that the two strings are equal.
elias

Re:questions about library functions

Post by elias »

didnt know about strcmp and strcpy. well that solves ym problem
Post Reply