我坚持了valgrind用我的代码报告的这个问题。我正在向全局数组中添加pids(这样做是因为我想在一个信号处理程序中打印pids)。
valgrind似乎对将pid放入数组的代码行有问题:
PIDs[i] = cPID;
这是我的代码:
pid_t *PIDs;
void funct(int i) {
//doing unrelated stuff
rc = fork();
if(rc==-1) {
//error
}
else if(rc==0) {
//child (this runs first b/c I used sleep on parent)
rc=getpid();
//execvp call
}
else {
PIDs[i]=rc;
}
}
int main() {
//calculate no. of PIDs - I checked this and it reports the correct number
int i = 8;
//allocate memory for PIDs array
PIDs = malloc(sizeof(pid_t)*number_of_PIDS); //number_of_PIDs report 8
funct(i);
free(PIDs);
}
Valgrind错误如下:
==6310== LEAK SUMMARY:
==6310== definitely lost: 0 bytes in 0 blocks
==6310== indirectly lost: 0 bytes in 0 blocks
==6310== possibly lost: 0 bytes in 0 blocks
==6310== still reachable: 24 bytes in 1 blocks
==6310== suppressed: 0 bytes in 0 blocks
==6310== Reachable blocks (those to which a pointer was found) are not shown.
==6310== To see them, rerun with: --leak-check=full --show-leak-kinds=all
==6310==
==6310== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)
==6310==
==6310== 1 errors in context 1 of 1:
==6310== Invalid write of size 4
==6310== at 0x4010F3: funct
==6310== by 0x401496: main
==6310== Address 0x51db388 is 0 bytes after a block of size 24 alloc'd
==6310== at 0x4C2A0B0: malloc (in /usr/lib64/valgrind/vgpreload_memcheck-amd64-linux.so)
==6310== by 0x40134F: main
==6310==
==6310== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)
我做错什么了吗?或者有没有其他的建议去哪里寻找valgrind错误?
最佳答案
地址0x51db388是大小为24的块后的0字节
不可能是8码。24除以8等于3,pid_t
几乎肯定是4。
您可能为6个pid_t
分配了空间,但最终却使用了9个(包括0到8个)。
关于c - 我将PID放入数组中,并且valgrind告诉我超出范围或分配的内存太少,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58422012/