[英]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.