的valgrind在0x4007A0报告尺寸8为什么我的C串堆叠已经无效写报告的valgrind-3.1.1
的无效写:由0x4008F8 ArrayCstringPush
:主要
地址0x4A0A450是大小为8的一个块后0字节alloc'd
在0x4905D27:释放calloc
以0x .......:ArrayCstringNew
by 0x ........:主要
为什么要报告这个错误?以及如何解决这个问题。 谢谢!
//arrayOfCstring.h
typedef struct {
int numOfElems;
int size;
int allocSize;
char** elems;
//size_t elemAllocSize;
} ArrayCstring;
void ArrayCstringNew(ArrayCstring *s,int allocS)
{
s->allocSize=allocS;
s->numOfElems=0;
s->size=0;
s->elems=(char **)calloc(s->allocSize,sizeof(int));
assert(s->elems!=0);
}
void ArrayCstringGrow(ArrayCstring *s){
if(((s->numOfElems)+1)>(s->allocSize)){
s->allocSize=(s->allocSize)*2;
s->elems=(char**)realloc(s->elems,(s->allocSize)*sizeof(int));
}
}
void ArrayCstringPush(ArrayCstring *s,char *elem,int lengthOfElem){
ArrayCstringGrow(s);
//(s->elems)[s->numOfElems]=(char *)malloc(lengthOfElem);
(s->elems)[s->numOfElems]=(char *)calloc(lengthOfElem,sizeof(int));
printf("start to realloc numOfElem is %i, allocSize is %i\n",s->numOfElems,s->allocSize);
strcpy((s->elems)[s->numOfElems],elem);
//assert((s->elems)!=0);
printf("push %s\n",s->elems[s->numOfElems]);
s->numOfElems+=1;
}
char *ArrayCstringIndex(ArrayCstring *s,int i)
{
//assert((s->numOfElems)>i);
return s->elems[i];
}
void ArrayCstringDelete(ArrayCstring *s)
{
int a=0;
for(;a<(s->numOfElems);++a){
free((s->elems)[a]);
}
free(s->elems);
}
//MAIN FUNCTION
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include "arrayOfCstring.h"
int main(void){
ArrayCstring *ep;
ep =(ArrayCstring *)malloc(1000);
ArrayCstringNew(ep,2);
ArrayCstringPush(ep,"ysdfsd",7);
printf("start to \n");
ArrayCstringPush(ep,"1213423",8);
int a;
for(a=0;a<2;++a){
char *str=ArrayCstringIndex(ep,a);
printf("string is %s\n",str);
}
ArrayCstringDelete(ep);
}
这是否解决这一问题的valgrind报告? - 对'malloc'的调用是在'#include' – Flexo 2012-02-28 14:58:32
到awoodland之后:“arrayOfCstring.h”包含在#include –
wei
2012-02-29 02:40:18
到hmjd之后:你是对的。谢谢! – wei 2012-02-29 03:14:34