标签:style blog class code color width
1,指针没有指向一块合法的区域
1指针没有初始化
|
1
2
3
4
5
6
7
8
9
10
11
12
13 |
#include <stdio.h>#include <string.h>struct
aa{ char
*pa; char
c;}ssa,*ssb;void
main(){strcpy(ssa.pa,"abc");printf("%s \n",ssa.pa);} |
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 |
#include <stdio.h>#include <string.h>#include <stdlib.h>struct
aa{ char
*pa; char
c;}ssa,*ssb;void
main(){ssb=(struct
aa *)malloc(sizeof(struct
aa));strcpy(ssb->pa,"ac");printf("%s \n",ssb->pa);} |
ssa 定义时 只给 pa指针分配了内存,内存没有初始化,指针指向的地址是随机的(在GCC 中好像未初始化的指针指向 0)。
malloc 只给 ssb 初始化了,没有给 pa初始化。
故访问指针指向的地址时会出现错误。
必须对指针进行初始化
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 |
#include <stdio.h>#include <string.h>#include <stdlib.h>struct
aa{ char
*pa; char
c;}ssa,*ssb;void
main(){ssa.pa=malloc(sizeof(char));strcpy(ssa.pa,"ac");printf("%s \n",ssa.pa);} |
2,没有分配足够的空间
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 |
#include <stdio.h>#include <string.h>#include <stdlib.h>struct
aa{ char
*pa; char
c;}ssa,*ssb;void
main(){printf("%d\n",sizeof(struct
aa));ssb=malloc(sizeof(int));ssb->c=‘D‘;printf("%c \n",ssb->c);printf("address of ssb ->%d\n",ssb);printf("address of ssb.pa ->%d\n",ssb->pa);printf("address of ssb.c ->%d\n",&(ssb->c));} |
书上说的例子好像不太对。
结构体为指针加char 按照4字节对齐需要8字节的空间。
malloc了4个字节的空间,依然可以访问。

书上的例子的错误是结构体内的指针没有初始化,而不是空间分配太小。
但是从规范上来说应该:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 |
#include <stdio.h>#include <string.h>#include <stdlib.h>struct
aa{ char
*pa; char
c;}ssa,*ssb; void
main(){ssb=(struct
aa *)malloc(sizeof(struct
aa));ssb->c=‘D‘;printf("%c \n",ssb->c);} |
3.
|
1
2
3
4
5
6
7
8
9
10
11
12 |
#include <stdio.h>#include <string.h>#include <stdlib.h>void
main(){char
*pa="abcdefg";char
*pb;pb=malloc(sizeof(char));strcpy(pb,pa);printf("%s \n",pb);} |

不知道是编译器不符合规范还是其他原因。依旧不会出错。
4 数组越界
|
1
2
3
4
5
6
7 |
#include <stdio.h>void
main(){int
pa[3]={1,2,3};printf("%d \n",pa[4]);} |
GCC对数组越界不进行任何处理,没有错误警告。

5 内存泄漏
内存要及时 free
6 内存释放
1。free后依然可以通过指针变量访问内存,要将 指针变量 p=NULL
2.在子函数中内部定义了一个数组,函数返回数组的指针。子函数中定义的数组,在函数返回时会自动销毁,返回的指针指向数组的内存,
3,内存使用太复杂,不知道那块已释放,那块未释放。
标签:style blog class code color width
原文地址:http://www.cnblogs.com/chen-/p/3705548.html