The problem is simple: sizeof((u_char)value)
returns 8. strlen fails. How to get a length of uchar's content?
Attempted
std::cout << "Data: " << (u_char *)data[0] << "\n"`;
u_char is defined 开发者_StackOverflow中文版in include/sys/*.h as unsigned char;
sizeof() returns the number of bytes required to store the variable. So sizeof(u_char) == 8 means it takes eight bytes to store one u_char.
The reason you are getting a segmentation fault is because (u_char *)data[0] means you want the first element in the data array, then treat it as a memory address and dump the data there. So if data[0] is 60, you are trying to std::cout whatever is at memory location 60. Since this memory location belongs to another application you get a segmentation fault (you are looking outside of your allowed segment of memory.)
Without knowing what data type u_char is, it is impossible to say how to get its length.
The problem is simple: sizeof((u_char)value) returns 8. strlen fails. How to get a length of uchar's content?
I get a feeling that u_char
is unsigned char
and value
is defined as u_char value[8]
So, to me, it looks like you are trying to extract the length of a buffer which is not NULL terminated. This is where strlen fails.
Here are some basics:
Given the code
unsigned char buf[2] = {'H', 'I'}; // not NULL terminated.
a. strlen(buf) will give undefined results as there is no terminating NULL in the buffer 'buf'.
b. sizeof(buf[0]) will give 1 on any implementation
c. sizeof(buf) will give 2, which is the sizeof the memory reserved for buf.
If the buffer is not used to represent strings (which are always NULL terminated), but just a sequnce of bytes potentially terminated by some marker/sentinel, in such a case, the length of the buffer needs to be calculated by counting the number of elements before the sentinel manually (for/while/do-while loop etc).
BTW, why not use std::vector or std::string?
If data[0] is a scalar value (e.g. not a pointer, especially to an ASCII or UTF-8 text string), then yes, this would be likely to seg fault. What you're doing in that case is taking the value at data[0] and telling the compiler to treat it as a pointer.
So, for instance, let's say you have the following:
char data[256];
strcpy(data, "Hello");
std::cout << "Data: " << (u_char *)data[0] << "\n"`;
The value at data[0] is the character 'H', which has a value of 72 (base 10). So you've just told the compiler to treat 72 as a pointer, and find a string at address 72, and print it out. That's unlikely to work.
Some operating systems specifically guard low addresses and deliberately seg fault when you try to access them to let you know you've written this kind of bug.
(sizeof(value)/sizeof(value[0])) * sizeof(u_char)
精彩评论