[英]valgrind complains: Invalid write of size 8, On malloc
我不知道为什么我在运行 Valgrind 时看到这个错误。
struct char_ctx {
int arr_size;
char **char_array;
};
void char_compile() {
struct char_ctx *ctx = malloc(sizeof(struct char_ctx*));
ctx->char_array = malloc((100) * sizeof(char *)); // I see error with this.
char **y = malloc((100) * sizeof(char *)); // I dont see error with this.
ctx->arr_size = 100;
}
int main(int ac, char **av)
{
char_compile();
return 0;
}
Valgrind 输出
==30585== Invalid write of size 8
==30585== at 0x108671: char_compile (temp.c:54)
==30585== by 0x1086A8: main (temp.c:63)
==30585== Address 0x522f048 is 0 bytes after a block of size 8 alloc'd
==30585== at 0x4C31B0F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==30585== by 0x10865B: char_compile (temp.c:53)
==30585== by 0x1086A8: main (temp.c:63)
代码正确执行。 我在ctx->char_array
上看到错误,但是当我使用char **y
,我没有看到错误。
问题出在这一行:
struct char_ctx *ctx = malloc(sizeof(struct char_ctx*));
您只是为指向struct char_ctx
的指针分配空间,而不是为struct char_ctx
分配空间。 正因为如此,对ctx->char_array
写入会超过分配内存的末尾。
你想要:
struct char_ctx *ctx = malloc(sizeof(struct char_ctx));
或者更好:
struct char_ctx *ctx = malloc(sizeof *ctx);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.