Have a
typedef struct person {
char name[20]
char surname[20]
} person_t;
I need to create a string like XXXXXX:YYYYYY with the function like
char* personToString(person_t *p). I tried to make it:
char* personToString(person_t* p) {
int n1,n2;
n1=strlen(p->name);
n2=strlen(p->surname);
char *p = (char*) malloc((n1+n2+2)*sizeof(char));
strcat(p,puser->name);
strcat(p,":");
strcat(p,puser->surname);
return p;
}
This give me a reasonable output but I have some errors testing with valgrind! I also think that there is a way more classy to write the function!
When you malloc memory for p the memory will hold garbage values. Strcat will append a string after the null character, but in an uninitialized string will hold random values.
Replace the first strcat with strcpy.
You need to
strcpy(p,puser->name);
not
strcat(p,puser->name);
malloc does not initialize the buffer to zero, so strcat is searching for a null byte in p first and probably not finding one, reading past the end of the buffer and thus crashing.
Instead of one strcpy plus two strcat you can also write one call to sprintf:
sprintf(p, "%s:%s", puser->name, puser->surname);
First you should call string copy, then strcat:
strcat(p,puser->name);
should be:
strcpy(p,puser->name);
because memory allocated with malloc function keeps values garbage, by doing strcat for first you are concatenating after garbage -- it also brings Undefined behaviour in your code.
You can use void* calloc (size_t num, size_t size); instead of malloc(), calloc function initialized allocated memory with 0 (then strcat() no problem).
Also dynamically allocated memory you should deallocate memory block using void free (void* ptr);) explicitly.
This looks good to me,
char* personToString( struct person_t *p )
{
int len = strlen(p->name) + strlen(p->surname) + 2; // holds ':' + NULL
char *str = malloc( len ); // Never cast malloc's return value in C
// Check str for NULL
if( str == NULL )
{
// we are out of memory
// handle errors
return NULL;
}
snprintf( str, len, "%s:%s", p->name, p->surname);
return str;
}
NOTE:
Never cast malloc's return value in C.
Use snprintf when multiple strcat is needed, its elegant.
free the return value str here in caller.
Fixed struct and char variables.
Related
I used this code to print some string,but it does not print any thing.What is the problem?
char* getNotFilledEncryptionParams(void)
{
char* nofilledStr;
char tmp[3];
const char * arr[]= {" P,"," Q,"," A,"," B,"," C,"," R,"," S0,","S1,","S2,","F1,","G1"};
for(i=0;i<11;i++)
{
if(filledParams[i] == 0)
{
strcpy(tmp,arr[i]);
strcat(nofilledStr,tmp);
}
}
return nofilledStr;
}
Usage:
int main(void){
char *remaining;
remaining = getNotFilledEncryptionParams();
printf("\r\n Remaining item:%s",remaining);
}
I think the problem is in const char * arr[] and I changed it,but the problem remains.
You didn't allocate any memory for noFilledStr, so its value is indeterminate and strcat(noFilledStr, tmp) is undefined.
Use malloc to allocate memory and initialize noFilledStr with the returned pointer:
char* noFilledStr = malloc(number_of_bytes);
The strings in arr are char[4], not char[3] (do not forget the null byte!). tmp is too small to hold them, so strcpy(tmp, arr[i]) writes out of bounds.
You are trying to build the string to return in the location pointed to by nofilledStr but this pointer is pointing somewhere as you do not initialize it. You could use a sufficiently large static char[] array if you do not have to deal with multiple threads. Otherwise, use malloc() and require the caller to free() the returned string when he is done with it.
I am getting a pointer to a string passed as an argument to the function, and I need to change a few characters in the string. I'm copying the string to a char array and editing what I need to just fine, but I need to change the original string that is being pointed to into the new char[] I just created.
The function has to return void, and because the pointer being passed is just a copy of the one from main, setting it to point to the new char[] won't do anything as it will just be deleted when the function ends, so I need to actually change the string being pointed to.
*str = &newstr[0]
This is giving me the compiler error: assignment makes integer from pointer without a cast.
*str = newstr
And this is segfaulting when I run the program.
Here is the full function:
void replace(char* str, char toReplace, char replaceWith) {
int strLen = strlen(src);
char newstr[strLen];
int i;
for (i = 0; i < strLen; i++) {
if (str[i] == toReplace)
newstr[i] = replaceWith;
else
newstr[i] = str[i];
}
// How to change the value of the string being pointed to by *str to now be newstr?
}
After digesting all the comments on your question, I've come to the understanding that you're trying to invoke your function in the following manner:
char * str = "string literal"; /* compiler should have warned you about assigning
string literal to non-const pointer. */
replace( str, 'i', 'u' );
printf( "%s\n", str );
Now, the problem with that is any attempts to modify the memory that str points to will be undefined behaviour.
Your attempt at a solution was to try to change the actual pointer inside the function. But to do so, your replace function would need to accept a char**, and then allocate new memory. That's not a nice approach in this case. You really just need to modify the string in-place:
void replace(char* str, char toReplace, char replaceWith)
{
while( *str )
{
if( *str == toReplace ) *str = replaceWith;
str++;
}
}
And how to deal with the string literal? Well, the solution is simple. Make an array:
char str[] = "string literal";
replace( str, 'i', 'u' );
printf( "%s\n", str );
How to change the value of the string being pointed to by *str to now
be newstr?
You can't due to (1) the way you pass str to the function as char *s and (2) because you declare newstr as a local variable in replace. (and probably for a whole host of other reasons that are not ascertainable from the limited section of code you posted)
When you pass a pointer to a function, the function receives a copy of the pointer with it very own and very different memory address. In other words when you declare the parameter char *str in your function parameter list, that creates a new pointer. (it still points to whatever is passed in str, but its variable address is very different from the original pointer address in the calling function - so nothing you do to the address of str will ever be reflected in the calling function.) If you want to assign a new address to a pointer in a function, you must pass the original address from the caller. e.g.
void replace(char **str, char toReplace, char replaceWith)
and then in your calling routine call it with:
replace (&origPtr, char toReplace, char replaceWith)
(as a style aside: don't use CamelCase variables in C, camelcase is proper)
Finally, since the address for newstr will be destroyed when you exit function replace, your only option for assigning the address of newstr to *str is to (1) declare newstr as static, or (2) dynamically allocate newstr (e.g. char *newstr = malloc (sizeof *newstr * strLen + 1);. Then you can assign the value of newstr to str. e.g.:
void replace(char **str, char toReplace, char replaceWith) {
int strLen = strlen(*str);
int i;
char *newstr = malloc (sizeof *newstr * strLen + 1);
if (!newstr) {
fprintf (stderr, "error: virtual memory exhausted.\n");
exit (EXIT_FAILURE);
}
for (i = 0; i < strLen; i++) {
if ((*str)[i] == toReplace)
newstr[i] = replaceWith;
else
newstr[i] = (*str)[i];
}
newstr[strLen] = 0; /* nul-terminate (or use calloc to allocate) */
free (*str); /* MUST have been dynamically allocated in caller */
*str = newstr;
}
(note: str must not have been statically declared in the calling function, and you must free the block of memory it points to or you will create a memory leak by overwriting the starting address to the block of memory it originally pointed to -- making it impossible to free the original block.)
All of these reasons are reasons why it is better to approach this problem by either changing the toReplace and replaceWith characters in place (presuming it str was an array and not a string-literal), or passing an additional array to fill with the replacement as a parameter (or as a pointer to allocate -- or return a pointer to a newly allocated block of memory containing the new string).
Let me know if you have further questions.
Why the size of the following allocated string (i.e. result) is not correct in the following code
#include <stdlib.h>
char *concat(const char *s1, const char *s2)
{
char *result;
result = malloc( strlen(s1) + strlen(s2) + 1 );
printf("%d", sizeof(result)); // <-- ????? ( it should be seven)
if ( result == NULL ){
printf("Error: malloc failed in concat\n");
exit(EXIT_FAILURE);
}
strcpy(result, s1);
strcpy(result, s2);
return result;
}
int main()
{
char *p;
p = concat("abc", "def");
return 0;
}
Edit:
I'm trying to allocate an enough size for the new string but for somehow the size is not correct.
In this case sizeof is evaluated at compile time, and it pays no attention to the size of the allocated block.
The expression returns the size of pointer, which is fixed for the hardware platform.
Unfortunately, there is no way of finding the allocated size returned by malloc. If you want to know the size of an allocated block, you need to store the size in a separate variable.
sizeof(result) will give the size of a pointer probably 4 or 8, so you cant use it for that.
Immediately after calling malloc you should check it's return value, on error it returns NULL, if the value is not NULL then it points to uninitialized content.
To get the length of a string you need strlen function, but if the contents are not initialised it would be undefined behavior.
You need to use strlen after you fill the buffer with data, the data is terminated with a '\0' byte which marks the end of the string, it wouldn't be there if you haven't initialized the data.
How to pass the param like char * as a reference?
My function uses malloc()
void set(char *buf)
{
buf = malloc(4*sizeof(char));
buf = "test";
}
char *str;
set(str);
puts(str);
You pass the address of the pointer:
void set(char **buf)
{
*buf = malloc(5*sizeof(char));
// 1. don't assign the other string, copy it to the pointer, to avoid memory leaks, using string literal etc.
// 2. you need to allocate a byte for the null terminator as well
strcpy(*buf, "test");
}
char *str;
set(&str);
puts(str);
You have to pass it as a pointer to the pointer:
void set(char **buf)
{
*buf = malloc(5 * sizeof(char));
strcpy(*buf, "test");
}
Call it like this:
char *str;
set(&str);
puts(str);
free(str);
Note that I have changed the malloc call to allocate five characters, that's because you only allocate for the actual characters, but a string also contains a special terminator character and you need space for that as well.
I also use strcpy to copy the string to the allocated memory. That is because you are overwriting the pointer otherwise, meaning you loose the pointer you allocate and will have a memory leak.
You should also remember to free the pointer when you are done with it, or the memory will stay allocated until the program ends.
C does not support pass by reference. But you can pass a pointer to your pointer, and set that:
void set(char **buf)
{
*buf = malloc(5*sizeof(char)); //5, to make room for the 0 terminator
strcpy(*buf,"test"); //copy the string into the allocated buffer.
}
char *str;
set(&str);
puts(str);
You to pass a pointer to a pointer, char**: there are no references in C.
void set(char** buf)
{
*buf = malloc(5); /* 5, not 4: one for null terminator. */
strcpy(buf, "test");
}
Note that:
buf = "test";
does not copy "test" into buf, but points buf to the address of the string literal "test". To copy use strcpy().
Remember to free() returned buffer when no longer required:
char* str;
set(&str);
puts(str);
free(str);
C is pass-by-value. There is no pass-by-reference.
In the example given above by hmjd, it should be:
strcpy(*buf, "test");
C cannot not pass function arguments by reference, C always passes them by value.
From Kernighan & Ritchie:
(K&R 2nd, 1.8 Call by value) "In C all function arguments are passed by "value""
To modify a pointer to T, you can have a pointer to pointer to T as the function argument type.
I have a simple doubt in char arrays. I have a structure:
struct abc {
char *charptr;
int a;
}
void func1()
{
func2("hello");
}
void func (char *name)
{
strcpy(abc.charptr, name); // This is wrong.
}
This strcpy will result in a crash since I do not have any memory allocated to the charptr.
The question is : For mallocing this memory, can we do
abc.charptr = (char *) malloc(strlen(name)); //?
strcpy(abc.charptr, name); // Is this (or strncpy) right ?
Is this right ?
If you were to use malloc() you need to remember to make room for the null-terminator. So use malloc(strlen(name)+1) before calling strcpy().
But in this case you should just use strdup() which does the allocation and copying in one go:
abc.charptr = strdup(name);
The memory returned by strdup() has been allocated with malloc() and hence must be disposed of with a call to free().
It needs to be:
abc.charptr = malloc(strlen(name)+1); ?
strcpy(abc.charptr, name);
The return value of strlen doesn't include space for the null zero '\0' at the end of the string.
You will also have to free your allocated memory at some point.
abc.charptr = (char *) malloc(strlen(name) + 1);
Note the +1, since you need space for the null terminator. Then strcpy() will be fine.