动态堆栈缓冲区溢出
=================================================================
==42==ERROR: AddressSanitizer: dynamic-stack-buffer-overflow on address 0x7ffc56ba144e at pc 0x00000031c726 bp 0x7ffc56ba13d0 sp 0x7ffc56ba0b90
READ of size 15 at 0x7ffc56ba144e thread T0
#6 0x7face5f830b2 (/lib/x86_64-linux-gnu/libc.so.6+0x270b2)
Address 0x7ffc56ba144e is located in stack of thread T0
Shadow bytes around the buggy address:
0x10000ad6c230: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
(省略节省篇幅)
==42==ABORTING
char[]数组直接赋值给string时,按理来说会正常运行,但貌似是LeetCode本身分配的资源的问题,在执行本句时提示动态堆栈缓冲溢出。
char result_ch[size];
i=0;
for(queue q:qs){
while(!q.empty()){
result_ch[i]=q.front();
q.pop();
i++;
}
}
string result = result_ch;//[1&2-leetcode栈溢出]
return result;
循环将char加在str的后面,这也是LeetCode题解中所使用的的方式。
对于string的实现,C++和Java中的方式有很大不同。
我们知道在Java中,String是指向常量区静态常量的,加了一个字符所形成的新字符串会生成一个新的字符串,在常量区开辟新的空间存储。一个循环下来,形成了大量的不必要的的冗余字符串,这样就造成了极大的空间浪费。所以这种赋值方法对于Java来说可行,但不可取(这也是StringBuffer存在的必要性)。
但在C++中,string本质上是一个char数组,存有该char数组的头指针,故此方法不会造成资源的浪费。
与Java中的StringBuffer功能类似。
string result;
i=0;
for(queue q:qs){
while(!q.empty()){
//result_ch[i]=q.front();
result+=q.front();
q.pop();
i++;
}
}
return result;
运行成功并提交通过