假設該輸入數據:
char input[] = {
0x01, 0x02, 0x0a, 0x0b, /* A 32bit integer */
'h', 'e', 'l', 'l', 'o', 0x00,
'w', 'o', 'r', 'l', 'd', 0x00,
0x00 /* Necessary to make the end of the payload. */
};
在開始一個32整數給出:
const size_t header_size = sizeof (uint32_t);
解析輸入可以通過識別「串」來完成的第一字符和存儲指向它的指針,然後精確地移動到找到的字符串很長(1+),然後重新開始,直到達到輸入的結尾。
size_t strings_elements = 1; /* Set this to which ever start size you like. */
size_t delta = 1; /* 1 is conservative and slow for larger input,
increase as needed. */
/* Result as array of pointers to "string": */
char ** strings = malloc(strings_elements * sizeof *strings);
{
char * pc = input + header_size;
size_t strings_found = 0;
/* Parse input, if necessary increase result array, and populate its elements: */
while ('\0' != *pc)
{
if (strings_found >= strings_elements)
{
strings_elements += delta;
void * pvtmp = realloc(
strings,
(strings_elements + 1) * sizeof *strings /* Allocate one more to have a
stopper, being set to NULL as a sentinel.*/
);
if (NULL == pvtmp)
{
perror("realloc() failed");
exit(EXIT_FAILURE);
}
strings = pvtmp;
}
strings[strings_found] = pc;
++strings_found;
pc += strlen(pc) + 1;
}
strings[strings_found] = NULL; /* Set a stopper element.
NULL terminate the pointer array. */
}
/* Print result: */
{
char ** ppc = strings;
for(; NULL != *ppc; ++ppc)
{
printf("%zu: '%s'\n", ppc - strings + 1, *ppc)
}
}
/* Clean up: */
free(strings);
如果您需要在分裂複製,通過
strings[strings_found] = strdup(pc);
替換該行
strings[strings_found] = pc;
和使用之後添加清理代碼和ING strings
free()
前:
{
char ** ppc = strings;
for(; NULL != *ppc; ++ppc)
{
free(*ppc);
}
}
上面的代碼假定至少有1 '\0'
(NUL
又名空字符)跟在有效負載之後。
如果後面的條件沒有得到滿足,您需要定義任何其他終止序列/ around或需要知道其他來源的輸入大小。如果你不是你的問題是不可解決的。
上面的代碼需要以下標題:
#include <inttypes.h> /* for int32_t */
#include <stdio.h> /* for printf(), perror() */
#include <string.h> /* for strlen() */
#include <stdlib.h> /* for realloc(), free(), exit() */
,以及它可能需要以下定義之一:
#define _POSIX_C_SOURCE 200809L
#define _GNU_SOURCE
或什麼別的你的C編譯器要求做出strdup()
可用。
如果您不需要重新使用其他緩衝區,可以將字符串保存在那裏,只需使用指向它們開始的指針即可。它們已經被NUL終止。 –
@ ThomasPadron-McCarthy我在一段時間內沒有做太多的事情,我該如何再次移動指針的位置? –
或者,如果你確實需要重新使用緩衝區,你可以找到每個字符串的第一個字符和'strcpy()'或'strdup()'它。無論哪種方式,都要確保最後一個字符串也是以null結尾的,否則將其作爲特殊情況處理。 –