雖然代碼正在編譯並正確顯示輸出,但是當我運行「valgrind」時,它顯示以下錯誤。因爲我沒有valgrind的背景知識,所以我很難理解這一點。代碼中的內存錯誤和可能的解決方案
Invalid write of size 1
==14657== at 0x4EAE10C: _IO_default_xsputn (genops.c:480)
==14657== by 0x4E7CF81: vfprintf (vfprintf.c:1630)
==14657== by 0x4EA3813: vsprintf (iovsprintf.c:43)
==14657== by 0x4E85A06: sprintf (sprintf.c:34)
==14657== by 0x400622: copy_id_name (assign2a.c:12)
==14657== by 0x40065E: main (assign2a.c:21)
==14657== Address 0x51f204b is 0 bytes after a block of size 11 alloc'd
==14657== at 0x4C2B6CD: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==14657== by 0x400600: copy_id_name (assign2a.c:11)
==14657== by 0x40065E: main (assign2a.c:21)
==14657==
請解釋一下實際的錯誤和解決方法是什麼,以消除此錯誤。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/** Returns a pointer to allocated memory containing string in form "<id>=<name>" */
char *copy_id_name(const char *id, const char *name) {
char *ptr = NULL;
size_t len;
// Compute required length
len = strlen(id) + strlen(name); // [sic]
ptr = malloc(len-2); // [sic]
sprintf(ptr, "%s=%s", id, name);
return ptr;
}
int main(int argc, char *argv[])
{
char *ptr;
if (argc > 2) {
ptr = copy_id_name(argv[1], argv[2]);
} else {
ptr = copy_id_name("666", "badname");
}
printf("result: [%s]\n", ptr);
return 0;
}
你的valgrind選項是什麼? – vad