所以我有这个程序在我的家用机器上编译很好,但是一旦我在大学服务器上编译它就会打破......:/这对我的屁股来说是一个巨大的痛苦.我不知道可能导致错误的位置或原因.我首先从大学的valgrind报告开始.
==13527== Memcheck, a memory error detector
==13527== Copyright (C) 2002-2012, and GNU GPL'd, by Julian Seward et al.
==13527== Using Valgrind-3.8.1 and LibVEX; rerun with -h for copyright info
==13527== Command: ./main stock.dat coins.dat
==13527==
==13527== Invalid write of size 8
==13527== at 0x402762: load_data (in /RMIThome/shr/5/s3234575/Assignments2/main)
==13527== by 0x4028BE: main (in /RMIThome/shr/5/s3234575/Assignments2/main)
==13527== Address 0x6172676f72502074 is not stack'd, malloc'd or (recently) free'd
==13527==
==13527==
==13527== Process terminating with default action of signal 11 (SIGSEGV)
==13527== General Protection Fault …
Run Code Online (Sandbox Code Playgroud) 这是C++中的一段简单代码,它只为一个名为Foo的类的实例动态分配内存,并且忘记以后释放内存.让我们假设Foo非常简单.
int main() {
Foo *abcd = new Foo();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
由于程序终止,它真的是内存泄漏吗?如果我重新运行此程序,先前分配的内存是否可用于分配?
这是等效的Java代码:
public static void main(String[] args) {
Foo abcd = new Foo();
}
Run Code Online (Sandbox Code Playgroud)
由于程序快速终止,如果垃圾收集器没有足够的时间来释放内存怎么办?如果我重新运行此程序,先前分配的内存是否可用于分配?
甚至
int
main () {
return 0;
}
Run Code Online (Sandbox Code Playgroud)
泄漏记忆.确实,运行valgrind [0]输出
==21013== HEAP SUMMARY:
==21013== in use at exit: 72,704 bytes in 1 blocks
==21013== total heap usage: 1 allocs, 0 frees, 72,704 bytes allocated
==21013==
==21013== LEAK SUMMARY:
==21013== definitely lost: 0 bytes in 0 blocks
==21013== indirectly lost: 0 bytes in 0 blocks
==21013== possibly lost: 0 bytes in 0 blocks
==21013== still reachable: 72,704 bytes in 1 blocks
==21013== suppressed: 0 bytes in 0 blocks
Run Code Online (Sandbox Code Playgroud)
为什么会这样?如果Valgrind应该使用c ++进行泄漏检查失败,我应该如何亲自检查内存泄漏?
[0], …
在测试文档中,我发现我被问到以下代码中的问题是:
#include <iostream>
#include <stdlib.h>
#include <string.h>
using namespace std;
int main()
{
char* a = (char*) malloc (20);
char* b = (char*) malloc (20);
strcpy(b, "Secure Coding");
strcpy(a, "Insecure Coding");
a = b;
cout << a << endl;
cout << b << endl << endl;
free(a);
free(b);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
它是什么?