Dynamic memory allocation with strings

My main query is around the allocation of the memory for msg. I know there are memory allocation functions like malloc and such that can safely allocate memory for you. But what happens if one does not know for example how long fname is, since it could contain anything, as well as whatever else we want to put into message, in this case "Forename: ". In the above example I would assume the best thing to do would be to use malloc to allocate enough space to contain everything. Basically, what if it is impossible to calculate the amount of space required to hold everything in the array?.. I just wanted to know whats the best way to work with strings and memory allocation in C?

>I was just wondering, is it safe to do something like this?
No, an uninitialized pointer doesn't point to infinite usable memory.

>Basically, what if it is impossible to calculate the amount
>of space required to hold everything in the array?
Then you've done something wrong. You should always be able to calculate the size of your memory blocks to within a reasonable margin of waste, or you should be able to incrementally resize your blocks until all of the data is stored.

In your specific case, it's possible to calculate the necessary size for msg by taking the length of fname and adding it to the length of the format string. Alternatively you could use something like snprintf, which is generally better at giving you more information.

For things like streamed input where you simply cannot calculate the final length ahead of time, you're stuck with using a fixed-size block to read chunks and growing the result buffer until there aren't any more chunks.

>> int totalLen = strlen(formatstr) + strlen(name);
"%s" will be counted. The totalLen should be 41 but obtained totalLen is 43.
And,
>> len = sprintf(NULL,"This is my forename: %s",fname);
seems to work perfectly!!!
Is there an assurance that the string will not be written if NULL is passed? I believe not. Is this undefined behavior?

Casting the return of malloc is not a good practice neither.
sizeof(char) is redundant since char is a byte. It would be better to sizeof(*buffer) in that way if the pointer type gets changed still works. Forgot to add +1 in malloc, for the '\0'.

free(buffer);

freeing memory that it might not be allocated is a no no. Check that malloc was succesful.

> >> len = sprintf(NULL,"This is my forename: %s",fname);
> seems to work perfectly!!!
> Is there an assurance that the string will not be written if NULL is passed?
> I believe not. Is this undefined behavior?
It certainly is undefined behaviour.

However, if you have a C99 compiler, then you have snprintf() as well. It is legal to pass NULL to this in order to measure the length of a formatted string.

len = sprintf(NULL,"This is my forename: %s",fname);
seems to work perfectly!!!
Is there an assurance that the string will not be written if NULL is passed? I believe not. Is this undefined behavior?

According to the C99 Standard, 7.19.6.6.3, "The sprintf function returns the number of characters written in the array, not counting the terminating null character, or a neg ative value if an encoding error occurred".

So in the case of NULL in the first argument, sprintf can not write any characters in the array and so MUST return -1 in C99-compliant compilers. If you are lucky with one compiler (such as microsoft), it really means nothing. IMHO anyone should avoid to use non-portable hacks.

int totalLen = strlen(formatstr) + strlen(name);
I would try to avoid this kind of statements since the order of evaluation of the two functions is not defined. If one function affects the result of the other, then side effects will result.

There are no side effects in strlen, except may be errno.

char* buffer = (char*) malloc (sizeof(char) * totalLen); // allocate memory
Casting the return of malloc is not a good practice neither.sizeof(char) is redundant since char is a byte. It would be better to sizeof(*buffer) in that way if the pointer type gets changed still works. Forgot to add +1 in malloc, for the '\0'.

Yes it's right. sizeof(*buffer) * (len + 1) will be correct.

free(buffer);
freeing memory that it might not be allocated is a no no. Check that malloc was succesful.

> I think it simply wouldn't compile without explicit typecast to (char*).
Only in two cases, neither of them good.
1) you're using a pre-ansi compiler, where malloc returns the previous 'any' pointer type of char*. Since ANSI first came out in 1989 (that's 20 years ago!), why are you still using such a fossil?
2) you're using a C++ compiler to compile C code. In which case, learn to use the correct tool for the job. Don't mung your programs into polyglots just to make them compile as C or C++. All that leads to is code which is both bad C and bad C++.

You don't need to cast malloc in a valid ANSI C program, compiled with an ANSI C compiler.

This function will perform the allocation (with malloc) and then use that allocated space as the sprintf output buffer. You should free the memory when you're finished with it. It returns a negative value for any errors, so you may want to check for that.

I believe this is a GNU C extension, so it may not be supported on every platform.

I have a 2d matrix with dimension (3, n) called A, I want to calculate the normalization and cross product of two arrays (b,z) (see the code please) for each column (for the first column, then the second one and so on).
the function that I created to find the ...

Write a C program that should create a 10 element array of random integers (0 to 9). The program should total all of the numbers in the odd positions of the array and compare them with the total of the numbers in the even positions of the array and indicate ...