【发布时间】:2019-11-11 08:01:25
【问题描述】:
我们知道strcat() 接收指向目标数组的指针作为参数并将它们与源字符串连接。目标数组应该足够大以存储连接的结果。最近我发现 strcat() 仍然可以按预期执行,对于小程序,即使目标数组不够大,无法添加第二个字符串。我开始浏览 * 并发现 couple - answers 这个问题。我想更深入地了解当我在下面运行这段代码时硬件层到底发生了什么?
#include<iostream>
#include<iomanip>
#include<cmath>
#include<cstring>
using namespace std;
int main(){
char p[6] = "Hello";
cout << "Length of p before = " << strlen(p) << endl;
cout << "Size of p before = " << sizeof(p) << endl;
char as[8] = "_World!";
cout << "Length of as before = " << strlen(as) << endl;
cout << "Size of as before = " << sizeof(as) << endl;
cout << strcat(p,as) << endl;
cout << "After concatenation:" << endl;
cout << "Length of p after = " << strlen(p) << endl;
cout << "Size of p after = " << sizeof(p) << endl;
cout << "Length of as after = " << strlen(as) << endl;
cout << "Size of as after = " << sizeof(as) << endl;
return 0;
}
运行此代码后,数组 p[] 的长度为 12,p[] 的大小为 6。这样的长度如何物理存储在这样的数组大小上?我的意思是这个数组的字节数是有限的,这是否意味着 strlen(p) 函数只查找 NULL 终止符,并一直计数直到找到它并忽略该数组的实际分配大小。并且 sizeof() 函数并不真正关心数组中的最后一个元素(专门为空字符分配)是否存储空字符。
【问题讨论】:
-
堆溢出可能吗?稍等片刻,当你开始编写递归函数时,你可能会实现 Stack Overflow。