How to convert u_char* to char[] in C

Go To StackoverFlow.com

2

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?

2012-04-05 02:43
by user1314238


3

Your newValue is of type char, and for all intents and purposes, your myArray is of type char*.

First off, I'm going to assume that you're using memcpy correctly, and that you're passing in 3 parameters instead of 2, where the 3rd parameter is the same as the one you use in strncpy.

When you try using strncpy or memcpy, you're going beyond the one character "limit" in newValue when attempting to copy everything to myArray.

The fix should be quite simple:

u_char* newValue = requests->requestvb->val.string;

Once you've done that, this should work. Of course, that's assuming that the size of myArray is in fact greater than or equal to 255 :)

As a side note (and this should go without saying), please make sure that your myArray has 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.

2012-04-05 02:48
by K Mehta
Thanks! This solved my problem - user1314238 2012-04-05 03:01
Glad I could hel - K Mehta 2012-04-05 03:04
Ads