I'm encoding the contents of a message struct into a buffer.
int encode(const struct message *msg, unsigned char *buffer, size_t max_size)
{
if (buffer == NULL)
return -1;
unsigned char *buf_pos = buffer;
unsigned char *ep = buffer + max_size;
if (buf_pos + 1 <= ep) {
*buf_pos++ = SYNC_WORD_1;
} else {
return buf_pos - buffer;
}
.
.
.
}
When I call encode(&message, "", 1024);
I encounter a segmentation fault as expected. My understanding is that the segfault is caused by an attempt to access memory not allocated to the program, since ""
will contain just the null terminator and I'm passing it in place of a pointer.
The problem I'm having is when I try to handle this error. I haven't found a way to identify the invalid input that doesn't either cause a false-positive with valid inputs or another segfault.
So what's the correct way to weed out this kind of input?
答案 0 :(得分:2)
这不可能。
你基本上要求&#34;给出一个指针,我怎样才能确保那里有n个可写空间的字节?&#34;这是一个C对你没有帮助的问题。
从根本上说,因为指针只是地址,所以在与每个指针值相关联之后,没有其他类型的元信息。
您可以检查指针是否为NULL
,但这基本上是您可以确定的唯一指针值无效。非便携式(特别是在嵌入式目标上)你可以聪明地检查指针是否在各种已知的不可写区域中,但这仍然非常粗糙。
答案 1 :(得分:0)
我猜你在buf_pos中复制它时没有检查缓冲区的大小 尝试访问buf_pos + 1时,您可能会进入一些您无法访问的内存,从而导致分段错误。 你在可执行文件上尝试使用了valgrind吗?
答案 2 :(得分:0)
当提出有关运行时问题的问题时,正如这个问题所做的那样,发布实际输入,预期输出,实际输出,最重要的是,发布干净编译的代码后代码很短,并且仍然存在问题。
以下代码将处理指向仅包含NUL字节的字符串的指针。
但是,这不是唯一的问题。如果传入的缓冲区指针可能指向只读内存中的char数组,那么发布的代码仍然会导致seg fault事件。
int encode(const struct message *msg, unsigned char *buffer, size_t max_size)
{
if (buffer == NULL)
return -1;
if( strlen(buffer) == 0 )
return -1;
unsigned char *buf_pos = buffer;
unsigned char *ep = buffer + max_size;
if (buf_pos + 1 <= ep)
{
*buf_pos++ = SYNC_WORD_1;
}
else
{
return buf_pos - buffer;
}
.
.
.
}
为了能够为您提供更多帮助,您需要发布将调用此函数的方案。