I am working with snmp and the requests->requestvb->val.string function returns me a u_char* and I am trying to store that into a char[255].
u_char newValue = *(requests->requestvb->val.string)
char myArray[255];
I have tried a few approaches to copy the contents of newValue into myArray but everything seems to segfault. What am I doing wrong?
I have tried
memcpy(myArray, newValue);
Another attempt strncopy(myArray, newValue, sizeof(myArray));
What am I doing wrong?
Your
newValueis of typechar, and for all intents and purposes, yourmyArrayis of typechar*.First off, I’m going to assume that you’re using
memcpycorrectly, and that you’re passing in 3 parameters instead of 2, where the 3rd parameter is the same as the one you use instrncpy.When you try using
strncpyormemcpy, you’re going beyond the one character “limit” innewValuewhen attempting to copy everything tomyArray.The fix should be quite simple:
Once you’ve done that, this should work. Of course, that’s assuming that the size of
myArrayis in fact greater than or equal to 255 🙂As a side note (and this should go without saying), please make sure that your
myArrayhas a null terminating character at the end if you ever plan on printing it. Not having one after performing copy operations, and then trying to print is a very common mistake and can also lead to seg faults.