我试过以下程序.创建此程序的目的是发现有关堆栈大小的更多信息.
int main()
{
int nStack[100000000];
return 0;
}
Run Code Online (Sandbox Code Playgroud)
执行上述代码后,程序因堆栈大小分配而崩溃.堆栈的最大可能大小是多少?它是否适用于每个程序/计算机?可以增加吗?
我想知道为了知识.如果任何人都可以在C/C++中提供示例,那将非常有用.
我从这里了解到不需要std::initializer_list分配堆内存。这对我来说很奇怪,因为您可以在不指定大小的情况下获取std::initializer_list对象,而对于数组,您始终需要指定大小。尽管初始化器列表在内部几乎与数组相同(正如帖子所暗示的那样)。
我很难理解的是,C++ 作为静态类型语言,每个对象的内存布局(和大小)必须在编译时固定。因此,每个std::array都是另一种类型,我们只是从通用模板中生成这些类型。但对于std::initializer_list,此规则显然不适用,因为接收函数或构造函数不需要考虑内存布局(虽然它可以从传递给其构造函数的参数派生)。仅当类型堆分配内存并且仅保留存储来管理该内存时,这对我才有意义。那么差异就很像std::arrayand std::vector,对于后者,您也不需要指定大小。
但std::initializer_list不使用堆分配,正如我的测试所示:
#include <string>
#include <iostream>
void* operator new(size_t size)
{
std::cout << "new overload called" << std::endl;
return malloc(size);
}
template <typename T>
void foo(std::initializer_list<T> args)
{
for (auto&& a : args)
std::cout << a << std::endl;
}
int main()
{
foo({2, 3, 2, 6, 7});
// std::string test_alloc = "some string longer than std::string SSO";
} …Run Code Online (Sandbox Code Playgroud) 可能重复:
C阵列实例化 - 堆栈还是堆分配?
当动态分配包含char指针的struct时,实际的char指针会发生什么?它存放在哪里?
一旦结构被释放,char指针是否随之释放?
例如,考虑以下结构:
struct mix
{
int a;
float b;
char *s;
};
typedef struct mix mix;
Run Code Online (Sandbox Code Playgroud)
然后是以下代码为它分配内存:
int main()
{
mix *ptr = (mix*)malloc(sizeof(mix));
ptr->a = 3;
ptr->b = 4.5f;
ptr->s = "Hi, there, I'm just a really long string.";
free(ptr);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
被*s分配在堆栈上,然后用中解脱出来一起*ptr?我可以想象它确实是在堆栈上分配的,因为它没有以任何方式动态分配(除非malloc具有一些我不知道的功能).而且我认为"超出范围" *s将会解放*ptr.或者我完全错了?:)
非常感谢!
我有一个简单的C文件I/O程序,它演示了逐行读取文本文件,并将其内容输出到控制台:
/**
* simple C program demonstrating how
* to read an entire text file
*/
#include <stdio.h>
#include <stdlib.h>
#define FILENAME "ohai.txt"
int main(void)
{
// open a file for reading
FILE* fp = fopen(FILENAME, "r");
// check for successful open
if(fp == NULL)
{
printf("couldn't open %s\n", FILENAME);
return 1;
}
// size of each line
char output[256];
// read from the file
while(fgets(output, sizeof(output), fp) != NULL)
printf("%s", output);
// report the error if we didn't reach …Run Code Online (Sandbox Code Playgroud)