Let's say I want to modify char array using function.
I am always seeing people using malloc, calloc, or pointers to modify int, char, or 2D arrays.
Am I right, if I say, that string can be returned from function only if I use malloc, create that array pointer and return him? Then why not getting/altering string, by passing it to function parameter?
Isn't my demonstration, which is using char array in parameter easier, than allocating/freeing? Is my concept wrong, or why am I never seeing people passing arrays to function? I am only seeing codes with passing like "char *array", not "char array[]", using malloc etc, when I see this method of altering char array easy. Am I missing something?
#include
void change(char array[]){
array[0]='K';
}
int main(){
char array[]="HEY";
printf("%s\n", array);
change(array);
printf("%s\n",array );
return 0;
}
Answer
If you only need to change existing characters in the string, and the string will be in a variable, and you don't mind the side-effect of your original string being modified, then your solution may be acceptable and indeed easier. But:
What if you want to get a modified string, but also want to retain the original? To avoid destroying an arbitrary-sized original, you need to
malloc
space, make a copy, and modify that.And what if you want to extend the string? If your change is to add " YOU" to the string, it can't modify the original because there's no space for it--it'll cause a buffer overflow, since there's only 4 bytes allocated for "HEY" (three letters plus the null terminator). Again, the solution involves
malloc
ing space to work with.
Functions that make changes using your technique typically need a size
or length
parameter to avoid overflowing the array and causing a crash and a potential security risk. But although that avoids the overflow, there's still the question of what happens if there's not enough space: Silently drop some data? Pass back a flag or special value to indicate there wasn't enough space, and expect the caller to handle it? In the long run, it ends up easier to write it right the first time, and malloc
/calloc
the space and deal with having to free it up later and all that.
No comments:
Post a Comment