valgrind报告大小为8的无效写入
在0x4007A0:ArrayCstringPush
通过0x4008F8:main
在分配了大小为8的块之后,地址0x4A0A450为0字节
在0x4905D27:calloc
由0x .....:ArrayCstringNew
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);
}
最佳答案
代码中存在malloc()
和calloc()
的几种误用,可能是导致无效写入的原因。
更改:
ep =(ArrayCstring *)malloc(1000);
s->elems=(char **)calloc(s->allocSize,sizeof(int));
(s->elems)[s->numOfElems]=(char *)calloc(lengthOfElem,sizeof(int));
至:
ep = malloc(sizeof(ArrayCstring));
s->elems= calloc(s->allocSize,sizeof(char*));
(s->elems)[s->numOfElems]= strdup(elem);
分别。