Problem 1:
What's the result of the program:
class base {
public:
~base() {
printf("base disconcrete\n");
}
};
class child:public base {
public:
~child() {
printf("child disconcrete\n");
}
};
int main() {
base* b = new child();
delete b;
return 0;
}
Take notice that base* points to derive, so :
Only
"base disconcrete" is printed.
But if
child* c = new child();
delete c;
Problem 2:
char* getMem(void) {
char p[] = "hello world";
p[5] = 0x0;
return p;
}
void test(void) {
char *s = 0x0;
s = getMem();
printf(s);
}
int main() {
test();
return 0;
}
The result is Not Sure
Problem 3: Quite Dangerous
void f(char **p) {
*p += 2;
}
int main() {
char *a[] = {"123","abc","456"}, **r = a;
f(r);
printf("%s\r\n",*r);
return 0;
}
The result is 3
But if
void f(char **p) {
*p += 2;
}
void g(char **p) {
p += 2;
}
int main() {
char *a[] = {"123","abc","456"}, **r = a;
//f(r);
g(r);
printf("%s\r\n",*r);
return 0;
}
The result is still 123
Only
printf("%s\r\n",*(r+2)); output 456
Problem 4:
- class str{
- public:
- int x;
- char s[0];
- };
- class foo{
- public:
- str * p;
- };
- int main() {
- foo f = {0};
- str* p1 = NULL;
- if (f.p->s){
- printf("%d\n", f.p->s);
- }
- return 0;
- }
This sentence sets p to NULL:
- foo f = {0};
f.p is a pointer of str, so f.p is an offset. I.e., f.p->s = base address + 4
So the result is 4
Problem 5: Dangerous:
#include <stdio.h>
#include <assert.h>
int main()
{
const int i = 10;
int* p = (int*)&i;
*p += 10;
printf("%d\t%d\n", i, *p);
printf("%x\t%x\n", &i, p);
}
The value of i is 10, *p = 20. The address of i and p is same.
But for struct.
#include <iostream>
#include <assert.h>
using namespace std;
struct mbLJ{
int mb;
int LJ;
mbLJ(){
mb=0;
LJ=1;
}
};
int main()
{
const struct mbLJ hehe;
int* p = (int*)(&hehe.mb);
*p += 10;
printf("%d\t%d\n", hehe.mb, *p);
}
输出 10 10
对全局变量取地址不会出错,对全局变量的const修改直接程序崩溃:
const int j = 10;
int main()
{
const int i = 10;
int* p = (int*)&i;
int* q = (int*)&j;
*q += 10;
//*p += 10;
printf("%d\t%d\n", i, *p);
printf("%x\t%x\n", &i, p);
//printf("%d\t%d\n", j, *q);
//printf("%x\t%x\n", &j, q);
return 0;
}
#include <iostream>
#include <assert.h>
using namespace std;
struct mbLJ{
static int mb ;
int LJ;
mbLJ(){
mb=0;
LJ=1;
}
};
int mbLJ::mb = 0;//没有这句编译不会过,因为静态成员变量只是声明,没有实现定义。。。
int main()
{
const struct mbLJ hehe;
int* p = (int*)(&hehe.mb);
*p += 10;
printf("%d\t%d\n", hehe.mb, *p);
return 0;
}