You need to be sure, theres room for the addition in the resulting char* if you just want to add it.
Something like this would do:
Code:
#include <stdio.h>
#include <string.h>
#define LENGTH 80
int main(){
char str[LENGTH +1];
strncpy(str, LENGTH, "Something = ");
printf("%s\n", str);
if(strlen(str) < (LENGTH -1))
{ /* add a char */
str[strlen(str)] = '3';
str[strlen(str)] = '\0';
}
printf("%s\n", str);
return 0;
}
But you need to be sure, that you've already assigned enough memory to your string, befor the addition, and that you NULL terminates the string, else your program will have uncontrolable behavior.
But the memory failure will only occur when you dont know what you're doing, you could easily free() the previusly used memory after your snprintf() and have that available instead of using alot and never free it.
ie:
Code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define LENGTH 80
int main(){
char *str1, *str2;
str1 = (char*)malloc(LENGTH*sizeof(char));
str2 = (char*)malloc(LENGTH*sizeof(char));
if(str1 != NULL)
strncpy(str1, LENGTH, "Somethign = ");
printf("%s\n", str1);
if(str2 != NULL)
if(strlen(str1) < LENGTH)
if(sprintf(str2, "%s%c", str1, '3'))
free(str1);
/* memory previusly occupied by str1
* is now free to be used elsewhere */
printf("%s\n", str2);
free(str2);
/* memory previusly occupied by str2
* is now free to be used elsewhere */
return 0;
}