如何用new函数时打印文件名称和行号
时间: 2023-11-22 21:53:52 浏览: 31
在使用`new`函数来分配内存时,可以使用`__FILE__`宏和`__LINE__`宏来打印当前文件的名称和行号。例如:
```c++
#include<iostream>
using namespace std;
int main(){
int *p = new int[10];
cout << "Allocated " << sizeof(int)*10 << " bytes of memory at address " << p << " in file " << __FILE__ << " at line " << __LINE__ << endl;
delete[] p;
return 0;
}
```
运行结果如下:
```
Allocated 40 bytes of memory at address 0x55f2bda4a260 in file main.cpp at line 6
```
这样可以方便地跟踪内存分配和释放的位置。
相关问题
如何能通过重载new,打印申请内存时的文件名称和行号
可以通过重载new操作符来实现打印申请内存时的文件名称和行号。具体实现方法如下:
1.定义一个自定义的new操作符,重载该操作符,以便能够接收文件名称和行号的参数。
```c++
void* operator new(size_t size, const char* file, int line) {
void* ptr = malloc(size);
cout << "Allocating " << size << " bytes in " << file << " at line " << line << endl;
return ptr;
}
```
2.为了确保不影响应用程序的其他部分,可以使用一个宏来替代所有的new操作符。这个宏将会在每个new操作符调用时,传递当前的文件名称和行号。
```c++
#define new new(__FILE__, __LINE__)
```
这样,在每个new操作符调用时,就会传递当前的文件名称和行号,从而能够打印出相应的信息。
完整的代码示例如下:
```c++
#include <iostream>
#include <cstdlib>
using namespace std;
void* operator new(size_t size, const char* file, int line) {
void* ptr = malloc(size);
cout << "Allocating " << size << " bytes in " << file << " at line " << line << endl;
return ptr;
}
#define new new(__FILE__, __LINE__)
int main() {
int* p = new int;
delete p;
return 0;
}
```
输出结果:
```
Allocating 4 bytes in main.cpp at line 14
```
如何能通过重载new,打印申请内存时的文件名称和行号】
可以通过重载 `operator new` 函数来实现打印申请内存时的文件名称和行号。以下是一个示例代码:
```c++
#include <iostream>
#include <cstdlib>
void* operator new(size_t size, const char* file, int line) {
std::cout << "Allocating " << size << " bytes from " << file << ":" << line << std::endl;
return std::malloc(size);
}
#define new new(__FILE__, __LINE__)
int main() {
int* p = new int;
delete p;
return 0;
}
```
在上面的代码中,我们定义了一个重载的 `operator new` 函数,它接受三个参数:申请的内存大小、文件名和行号。然后我们使用 `#define new new(__FILE__, __LINE__)` 宏来替换原本的 `new` 操作符,使其在申请内存时自动传入当前的文件名和行号。
这样,在程序运行时,每次申请内存时都会打印出文件名和行号,方便我们进行调试。注意,这种方法只能用于调试,不能在生产环境中使用。