[英]Why is the below code giving “dereferencing type-punned pointer will break strict aliasing rules” & How to fix it?
[英]Is the code below correct? how to fix this code
下面的代码是否正确?
char *make_file_name(char *base)
{
char *file_name = strdup(base);
strcat(file_name, ".pcap")
return file_name;
}
如何解决
下面的代码是否正确?
编号说明:
char *make_file_name(char *base)
{
char *file_name = strdup(base); // 1
strcat(file_name, ".pcap") // 2
return file_name;
}
file_name
现在指向 memory 区域,该区域刚好足以容纳与base
指出的字符串长度相同的字符串。file_name
和".pcap"
- 但是没有足够的空间,所以它会写出边界,结果是未定义的行为。修复方法是为两个字符串分配足够的 memory:
char *make_file_name(const char *base) // may as well make it const
{
size_t blen = strlen(base);
char *file_name = malloc(blen + 5 + 1); // blen + strlen(".pcap") + 1 for `\0`
if(!file_name) return NULL;
memcpy(file_name, base, blen);
memcpy(file_name + blen, ".pcap", 5 + 1);
return file_name;
}
strdup()
为base
+ 1 的大小分配 memory 并将base
复制到分配的 memory 中。
在您的代码中,当您调用strcat()
时,没有足够的空间将file_name
与".pcap"
连接起来。 因此,将发生调用未定义行为的越界写入。
要解决此问题,您必须为两个字符串分配足够的 memory:
char *make_file_name(const char *base)
{
char *file_name = malloc(strlen(base) + 5 + 1);
if (file_name != NULL) {
strcpy(file_name, base);
strcat(file_name, ".pcap");
}
return file_name;
}
完成后请记住free()
memory:
char *str = make_file_name("file1");
// use str
free(str);
如果您使用的是 GNUC,您可以非常简单地做到这一点:
#include <stdio.h>
char* make_file_name(const char* base) {
char* buffer = NULL;
asprintf(&buffer, "%s.pcap", base);
return buffer;
}
在使用strdup
之前,您需要分配足够的 memory 。 你可以这样做:
char *file_name = malloc(strlen(base) + 6);
在if
条件之前然后在 function 完成之后,您需要使用free()
释放 memory
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.