I have this structure of Node
typedef struct Node{
unsigned int length;
char *string;
} Node;
And this operation which accepts a pointer to a Node
and tries to attach the provided string:
int setString(Node *node, char *string){
char *newString;
if(!isString(node) || !string) return 0;
newString = (char *) malloc(strlen(string)+1);
if(!newString) return 0;
/*THIS PART FAILS*/
strncpy(newString,string,sizeof(newString));
node->string = newString;
node->length = strlen(newString);
/*Which can be seen here*/
printf("Original String: %s\n",string);
printf("Copied String: %s\n",node->string);
return 1;
}
At the indicated part, I can see that the original string doesn't seem be copied over to node->string
. It copies over the first two characters, and then what follows is either garbage or just blank.
I checked this post and I am following the third case, which seems to work for the OP. Maybe I overlooked something, but just can't figure out where
strncpy(newString,string,sizeof(newString));
In this context sizeof
doesn't do what you want. Pass the size you allocated or don't use strncpy
. If you follow your own logic, you already trust string
since you took its strlen
when you called malloc
.
So you can safely use strcpy
instead.
If you're willing to go a little non-portable, you could get away with:
newString = strdup(string);
Your sizeof() call is causing your problem:
sizeof(newString);
newString is a pointer to a character is declared here:
char *newString;
And character pointers use (normally) 2,4 or 8 bytes (depending on the machines architecture). So it's clear, that you are only copy the first 2/4/8 bytes. Use strlen(string) + 1
for the number of characters to copy.
Or you can just use strcpy()
. This will take care of the terminating null byte. Since you are calling malloc()
correctly with strlen
there is no chance to cause a overflow with strcpy()
.
You can not use the sizeof()
in order to determine the string length.
You have to use the strlen(string)
function instead.
Also you need to set \\0
after copied symbols to terminate the string.
Not sure, but try directly this:
strncpy(node->string,string,strlen(newString));
Changing the length function to strlen .
(i tried to make the changes in code to bold)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.