簡體   English   中英

正確使用malloc和strcat以避免使用valgrind出現內存錯誤

[英]Correct use of malloc and strcat to avoid memory errors with valgrind

我已經在tempStorage中存儲了頂點:

typedef struct {
    int pred[8];
    int succ[8];
} arc_set;

arc_set tempStorage;

例如.pred是0,1,1,2,2和.succ是2,2,3,3,1

我做了一個char *links = malloc(sizeof(char) * 100); 存儲這些數字並像這樣打印它們:

            char *temp = malloc(10);

            for (int l = 0; l < 8; l++){

                    sprintf(temp, "%d-%d ", tempStorage.pred[l], tempStorage.succ[l]);
                    strcat(links, temp);

            }
            free(temp);

            fprintf(stdout, "Solution %d edges: %s",countLinks, links);
            fprintf(stdout, "\n");

使用sprintf然后使用帶有鏈接的strcat concat將temp格式的字符串存儲為“%d-%d”格式。

它確實可以正確打印所有內容,但是當我用valgrind --leak-check=full --track-origins=yes -v ./programname我得到了:

Conditional jump or move depends on uninitialised value(s)
==12322==    at 0x4C2C66A: strcat (vg_replace_strmem.c:307)
==12322==    by 0x4013CC: main (program.c:251)
==12322==  Uninitialised value was created by a heap allocation
==12322==    at 0x4C29BC3: malloc (vg_replace_malloc.c:299)
==12322==    by 0x401270: main (program.c:225)

其中c:251是strcat(links, temp); c:225是我的char *links = malloc(sizeof(char) * 100);

我使用strcat錯了嗎?還是這是什么問題?

默認情況下,您從malloc獲得的malloc不是零初始化的。 並且strcat會將新內容附加到字符串的末尾。 對於非零初始化的內存塊,該內存塊可能隨處可見。

您無需將整個links設置為零-僅第一個字節就足夠了。 仍然memset(links, 0, 100); malloc之后不會受到傷害。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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