When an array is passed to a function or memory is dynamically allocated, we will lose the size of an array at run-time.
#include <stdio.h>
#include <string.h>
int function ( char *arr)
{
strncpy(arr, "Shirley", sizeof(arr));
printf("\n In function, arr size %s",arr);
}
main()
{
char array[64] = {0};
int ret =0;
ret = function(array);
printf("\n arr size %s",array);
return;
}
In function, arr size Shir
arr size Shir
Exited: ExitFailure 15
When you do strncpy, the array size will be pointer size. So, it is good to store the array size somewhere or use memcpy, instead of strcpy. The good solution is to pass the length of an array along with the array as a separate argument.
#include <stdio.h>
#include <string.h>
int function ( char *arr, int len)
{
strncpy(arr, "Shirley", len);
printf("\n In function, arr size %s",arr);
}
main()
{
char array[64] = {0};
int ret =0;
ret = function(array, sizeof(array));
printf("\n arr size %s",array);
return;
}
In function, arr size Shirley arr size Shirley Exited: ExitFailure 18
This will not give the RETURN_LOCAL warning. Click here for RETURN_LOCAL
Comments
Post a Comment