問題は単純です: 8 をsizeof((u_char)value)
返します。strlen は失敗します。uchar のコンテンツの長さを取得するには?
試みた
std::cout << "Data: " << (u_char *)data[0] << "\n"`;
u_char は include/sys/*.h で unsigned char として定義されています。
問題は単純です: 8 をsizeof((u_char)value)
返します。strlen は失敗します。uchar のコンテンツの長さを取得するには?
試みた
std::cout << "Data: " << (u_char *)data[0] << "\n"`;
u_char は include/sys/*.h で 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.
問題は単純です: sizeof((u_char)value) は 8 を返します。strlen は失敗します。uchar のコンテンツの長さを取得するには?
私はそれが次のように定義されてu_char
いるunsigned char
と感じてい
ます。だから、私には、NULL で終了していないバッファの長さを抽出しようとしているように見えます。ここで strlen が失敗します。value
u_char value[8]
以下にいくつかの基本事項を示します。
コードを考えると
unsigned char buf[2] = {'H', 'I'}; // not NULL terminated.
を。strlen(buf) は、バッファ 'buf' に終端の NULL がないため、未定義の結果を返します。
b. sizeof(buf[0]) は、どの実装でも 1 を返します
c. sizeof(buf) は、buf 用に予約されたメモリのサイズである 2 を返します。
バッファーが文字列 (常に NULL で終了) を表すために使用されず、何らかのマーカー/センチネルによって終了される可能性のある一連のバイトのみである場合、そのような場合、バッファーの長さは、文字列の数をカウントして計算する必要があります。センチネルの前の要素 (for/while/do-while ループなど)。
ところで、std::vector または std::string を使用しないのはなぜですか?
(sizeof(value)/sizeof(value[0])) * sizeof(u_char)
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.