堆栈打印
#include <execinfo.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
void printStackTrace() {
void *callstack[128];
int frames = backtrace(callstack, 128);
char **strs = backtrace_symbols(callstack, frames);
printf("Call stack:\n");
for (int i = 0; i < frames; ++i) {
printf("%s\n", strs[i]);
}
free(strs);
}
int subtract(int a, int b) {
printStackTrace();
return a - b;
}
int add(int a, int b) {
return a + b;
}
int multiply(int a, int b) {
return a * b;
}
float divide(float a, float b) {
if (b != 0) {
return a / b;
} else {
printf("Error: Division by zero\n");
return 0;
}
}
int main() {
int sum = add(5, 3);
int difference = subtract(10, 4);
int product = multiply(6, 7);
float quotient = divide(8.0, 2.0);
printf("Sum: %d\n", sum);
printf("Difference: %d\n", difference);
printf("Product: %d\n", product);
printf("Quotient: %f\n", quotient);
return 0;
}
void printMemoryMap() {
char path[100];
sprintf(path, "/proc/%d/maps", getpid());
FILE *mapsFile = fopen(path, "r");
if (mapsFile) {
char buffer[256];
printf("Memory map:\n");
while (fgets(buffer, sizeof(buffer), mapsFile) != NULL) {
printf("%s", buffer);
}
fclose(mapsFile);
} else {
printf("Failed to open /proc/[pid]/maps\n");
}
}
void printStackTrace() {
printMemoryMap();
void *callstack[128];
int frames = backtrace(callstack, 128);
char **strs = backtrace_symbols(callstack, frames);
printf("Call stack:\n");
for (int i = 0; i < frames; ++i) {
printf("%s\n", strs[i]);
}
free(strs);
}