簡體   English   中英

valgrind 抱怨:大小為 8 的無效寫入,在 malloc 上

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

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM