【发布时间】:2014-08-25 18:07:49
【问题描述】:
为堆中的结构元素分配内存,但出现分段错误,请帮我修复
#include<stdio.h>
struct st
{
int i;
int *p;
char ch;
};
int main()
{
struct st *q; // creating object pointer *q
int i=89;
q->p=malloc(10);
printf("%d\n",*((q->p)-1)); // i m printing size allocated in heap?
q->p=&i; // storing address i in structure element *p
printf("%d\n",*(q->p)); // segmentation fault?
}
【问题讨论】:
-
1)
q:取消初始化。 2)*((q->p)-1):超出有效范围访问 3)q->p=&i;:内存泄漏。 -
@BLUEPIXY *((q->p)-1) :在我知道的有效范围之外访问,但在这个位置,没有存储 malloc 分配的字节,这就是我要打印的内容.
标签: c pointers malloc structure