我如何在我的C(或者原则上但在这种情况下不是C ++)程序中设置RAM,堆或堆栈使用的上限?我正在Windows 10上使用Visual Studio。
我有一个可以正常工作的程序(井,库和一个小程序,可以运行基本测试并将其演示给我正在辅导的人),我想展示一下内存分配失败时会发生什么。 (而且我不只是用一个笨拙的分配来做到这一点,因为它是链表,而且我想在这种情况下显示内存分配失败。)因此:我如何限制我的程序允许使用的内存量,我该在哪里做?我会在OS中做些什么告诉它“我要运行的应用程序只能使用X字节的RAM”(或者甚至告诉它限制堆或堆栈大小),我是否会在其中做些什么?编译器参数,链接器参数还是什么?
并且我编写的代码具有防止非法内存访问并随后在malloc(或在少数地方为calloc)返回NULL时崩溃的警告!因此,不必担心非法的内存访问和其他操作,我对自己的工作非常了解。
这是库头文件singleLinkList.h
的样子:
#ifndef SINGLELINKEDLIST_H
#define SINGLELINKEDLIST_H
#ifndef KIND_OF_DATA
#define KIND_OF_DATA 3
#endif // !KIND_OF_DATA
#include <stdlib.h>
#include <stdio.h>
typedef long long LL_t;
#if KIND_OF_DATA == 1
typedef float data_t;
#define DATA_FORM "%f"
#elif KIND_OF_DATA == 2
typedef double data_t;
#define DATA_FORM "%lf"
#elif KIND_OF_DATA == 3
typedef LL_t data_t;
#define DATA_FORM "%lld"
#else
typedef int data_t;
#define DATA_FORM "%d"
#endif // KIND_OF_DATA == 1, 2, etc...
struct listStruct;
// equivalent to `list_t*` within the .c file
typedef struct listStruct* LS_p;
// equivalent to `const list_t* const` within the .c file
typedef const struct listStruct* const LS_cpc;
typedef struct listStruct* const LS_pc;
int showSizes(void);
size_t queryNodeSize(void);
// returns NULL on failure
LS_p newList(void);
// returns NULL on failure (in memory alloc, at any point), or if given the NULL pointer
LS_p mkListCopy(LS_cpc);
// copies one list into another; leaves the destination unmodified upon failure
//returns a value indicating success/type of failure; returns 0 on success,
// various `true` values on failure depending on type
// 1 indicates simple allocation failure
// -1 indicates that you gave the NULL pointer
int copyList(LS_pc dst, LS_cpc src);
//destroys (frees) the given singly-linked list (the list_t* given, and all the list of nodes whose head it holds)
void destroyList(LS_p);
// destroys the list pointed to, then sets it to NULL
//inline void strongDestroyList(LS_p* listP) {
inline void strongDestroyList(struct listStruct** listP) {
destroyList(*listP);
*listP = NULL;
}
// Takes a pointer to a list_t
// returns how many elements it has (runs in O(n) time)
// If you don't understand what `O(n) time` means, go look up "Big O Notation"
size_t len_list(LS_cpc);
//prints a list; returns characters printed
int print_list(LS_cpc);
// gets the data at the specified index of the list; sets the output parameter on failure
data_t indexToData(LS_pc, const size_t ind, int* const err);
// will write the data at ind to the output parameter
//returns a value indicating success/type of failure; returns 0 on success,
// various `true` values on failure depending on type
// 1 indicates simple allocation failure
// -1 indicates that you gave the NULL pointer
int copyToPointer(LS_pc, const size_t ind, data_t* const out);
// gets the data at the specified index and removes it from the list; sets output param on failure
data_t popFromInd(LS_pc, const size_t ind, int* const errFlag);
// pops the first item of the list; sets the output param on failure
data_t popFromTop(LS_pc, int* const errFlag);
//returns a value indicating success/type of failure; returns 0 on success,
// various `true` values on failure depending on type
// 1 indicates simple allocation failure
// -1 indicates that you gave the NULL pointer
int assignToIndex(LS_pc, const size_t ind, const data_t value);
//returns a value indicating success/type of failure; returns 0 on success,
// various `true` values on failure depending on type
// 1 indicates simple allocation failure
// 2 indicates inability to reach the specified index, because it's not that long.
// -1 indicates that you gave the NULL pointer
int insertAfterInd(LS_pc, const size_t ind, const data_t value);
//returns a value indicating success/type of failure; returns 0 on success,
// various `true` values on failure depending on type
// 1 indicates simple allocation failure
// -1 indicates that you gave the NULL pointer
int appendToEnd(LS_pc, const data_t value);
//returns a value indicating success/type of failure; returns 0 on success,
// various `true` values on failure depending on type
// 1 indicates simple allocation failure
// -1 indicates that you gave the NULL pointer
int insertAtStart(LS_pc list, const data_t value);
#endif // !SINGLELINKEDLIST_H
这是运行演示/测试的main.c
的样子:
#ifdef __INTEL_COMPILER
#pragma warning disable 1786
#else
#ifdef _MSC_VER
#define _CRT_SECURE_NO_WARNINGS 1
#endif // _MSC_VER
#endif // __INTEL_COMPILER
#include "singleLinkList.h"
#include <stdio.h>
#include <string.h>
void cleanInputBuffer(void) {
char c;
do {
scanf("%c", &c);
} while (c != '\n');
}
void fill_avail_memory(void) {
size_t count = 0;
LS_p list = NULL;
size_t length;
data_t fin;
int err = 0;
const size_t nSize = queryNodeSize();
printf("nSize: %zu\n", nSize);
int last = -5;
printf("Do you wish to run the test that involves filling up available memory? "
"(only 'y' will be interpreted as an affirmative) => ");
char ans;
scanf("%c", &ans);
cleanInputBuffer();
if ((ans != 'y') && (ans != 'Y')) {
printf("Okay. Terminating function...\n");
return;
}
printf("Alright! Proceeding...\n");
list = newList();
if (list == NULL) {
printf("Wow, memory allocation failure already. Terminating...\n");
return;
}
print_list(list);
while (!(last = insertAtStart(list, (data_t)count))) {
++count;
}
length = len_list(list);
if (length < 5) {
print_list(list);
}
fin = indexToData(list, 0, &err);
strongDestroyList(&list);
printf("Last return value: %d\n", last);
if (!err) {
printf("Last inserted value: " DATA_FORM "\n", fin);
}
printf("Count, which was incremented on each successfull insert, reached: %zu\n", count);
printf("Length, which was calculated using len_list, was: %zu\n", length);
}
int main() {
printf("Hello world!\n");
showSizes();
LS_p list = newList();
print_list(list);
printf("Printing the list: "); print_list(list);
printf("Appending 5, inserting 1987 after it...\n");
appendToEnd(list, 5);
insertAfterInd(list, 0, 1987);
printf("Printing the list: "); print_list(list);
printf("Inserting 15 after index 0...\n");
insertAfterInd(list, 0, 15);
printf("Printing the list: "); print_list(list);
printf("Appending 45 to the list\n");
appendToEnd(list, 45);
printf("Printing the list: "); print_list(list);
//destroyList(list);
//list = NULL;
printf("Value of pointer-variable `list` is 0x%p\n", list);
printf("Destroying list...\n");
strongDestroyList(&list);
printf("Value of pointer-variable `list` is 0x%p\n", list);
printf("\n\n\n");
fill_avail_memory();
return 0;
}
([__INTEL_COMPILER
和_MSC_VER
的内容是为了废除对scanf
用法的废话。
所以:
而且我将从终端进行编译(而不是仅是“运行代码”,因为它是Visual Studio项目),如下所示:
cl singleLinkList.c -c
cl main.c /Zp4 /link singleLinkList.obj
任何帮助或关于寻找位置的建议,将不胜感激!谢谢!更新:人们建议工作对象。那似乎是C ++的事情。它可以在纯C语言中工作吗? (如果没有,那么虽然可能就足够了,但它并不是我想要的/希望的。)
如果要在用户/运行时级别执行此操作(并控制要测试的代码),则可以实现自己的safe_malloc()
,safe_calloc()
,safe_realloc()
和safe_free()
充当系统提供的对应对象的前端,并且会适当地增加或减少numberOfBytesUsed
计数器,但是如果numberOfBytesUsed
变得大于固定最大值将失败。
(注意,由于free()
不包含自由字节数,因此这样做有些棘手,因此您必须“隐藏”已分配缓冲区中的信息由safe_calloc()
和朋友返回-通常通过在调用代码所请求的代码之前分配额外的4个字节,将分配大小的值放在分配的前4个字节中,然后返回指向分配后第一个字节的指针-size字段)
如果您无法控制正在测试的代码(即该代码将直接调用malloc()
和free()
,并且您无法重写该代码以调用函数,那么您也许可以做一些令人讨厌的预处理器魔术(例如,您将包含在头文件中的#define calloc safe_calloc
),以诱使经过测试的代码做正确的事情。
关于限制所使用的堆栈空间的数量,我不知道有什么优雅的方法可以在代码级别强制实施。如果有一种方法可以通过编译器标志来强制执行它,则至少可以使程序在堆栈溢出的情况下可靠地崩溃,但这与受控/处理失败并不完全相同。
[使用Visual Studio,并出于演示目的,您可以使用_DEBUG
构建并使用_CrtSetAllocHook
挂接到CRT内存管理中。这将使程序可以监视内存分配,并在适当的时候触发故障。