To malloc() string in c with the same size of original string, the function 'testCode' must be given one additional item of information. Namely, the size of the original string.
#define SIZE_STRING 100
typedef char string[SIZE_STRING];
char *testCode(string str, size_t strSize)
Added 'strSize' (above) to the arguments of 'testCode' to provide the actual size of 'str'.
{
char *new_str;
// int limit = strlen(str);
// int new_limit;
new_str = (char*)calloc(strSize, sizeof(char));
Exchanged 'limit' for 'strSize' in order to allocate the correct size.
new_limit = strSize;
Exchanged 'strlen(new_str)' for 'strSize'. The previous term 'strlen(new_str)' will always be zero due to calloc()'s 'zeroing-out the new memory' feature.
printf("%d", new_limit);
return new_str;
}
void main()
{
char str[SIZE_STRING] = { "BLA BLA BLA" };
char *new_str;
new_str=testCode(str, sizeof(str));
}
A final thought...
The question was how to "malloc string in c with the same size of original string". Keep in mind that the 'size' of a character array differs from the 'length' of a character array. While the 'size' of an array is defined as the number of bytes (or perhaps elements) that make up the entire array, the 'length' of a C string is the number of characters found in the array up to the terminating '\0' character.
Hence if the question was actually how to "malloc string in c with the same length of original string", the above answer would still apply, except for the line:
new_str=testCode(str, sizeof(str));
would have to be changed to:
new_str=testCode(str, strlen(str)+1);