//DeclareFunTest.c
#include "LoadBuffer.h"
int main()
{
int i;
UserBuffer *buf;
buf=LoadBuffer();
printf("in main,%%p=%p,%%x=%x\n",buf,buf);
printf("size of int=%d\nsize of pointer=%d\n",sizeof(i),sizeof(buf));
long count=0;
for(i=0;isize;++i)
{
buf->buffer[i]=i+1;
count += buf->buffer[i];
}
printf("count=%d\n",count);
return 0;
}
// LoadBuffer.c
#include"LoadBuffer.h"
UserBuffer* LoadBuffer()
{
UserBuffer *ptr;
ptr=calloc(sizeof(UserBuffer),1);
ptr->size=BUFFER_SIZE;
printf("in LoadBuffer,%%p=%p,%%x=%x\n",ptr,ptr);
return ptr;
}
// LoadBuffer.h
#include
#include
#ifndef _LOAD_BUFFER_H_
#define _LOAD_BUFFER_H_
#define BUFFER_SIZE 102400
typedef struct{
int size;
int buffer[BUFFER_SIZE];
}UserBuffer;
//注释函数定义,则在调用时,程序默认返回int
//UserBuffer * LoadBuffer();
#endif
#makefile
DeclareFunTest: DeclareFunTest.c LoadBuffer.c LoadBuffer.h
gcc DeclareFunTest.c LoadBuffer.c -o DeclareFunTest -g -fPIC
run:
./DeclareFunTest
debug:
gdb DeclareFunTest -x DeclareFunTest.cmd
clean:
rm -rf libLoadBuffer.so DeclareFunTest
#DeclareFunTest.cmd
break LoadBuffer.c:7
commands
printf "in LoadBuffer,ptr=%lx\n",ptr
continue
end
break DeclareFunTest.c:8
commands
printf "in main,buf=%lx\n",buf
continue
end
r
注释掉LoadBuffer.h 中的函数原型定义,则在main函数中,gcc在编译时认为LoadBuffer函数返回int类型,而不是指针类型。
而在64为系统中,int占4个字节,而指针占8字节,导致数据截断,从而导致程序访问错误的内存空间。