我需要使用malloc将最后的char *传递给另一个函数。Valgrind抱怨我没有初始化*temp,所以我使用了malloc。我遇到的问题是没有分配内存?我一直在摆弄这个,但不知道如何修复它。
我是否在for循环期间丢失了内存分配?
然后再用sprint for newCatID?
如有任何建议,不胜感激。
char *allocateCategoryID(ThisType *menu)
{
char catID[ID_LEN]="";
char *temp;
char *newCatID;
char *end;
int idNum=0;
int i=0;
int j = 0;
temp = malloc(ID_LEN-1);
newCatID = malloc(ID_LEN*sizeof(char));
/*get catID which strlen(catID)= ID_LEN*/
for(i=1; i<ID_LEN; i++)/*FIRST VALGRIND ERROR IS HERE*/
{
temp[j]= catID[i];
j++;
}
idNum = strtol(temp, &end, 10);/*NEXT VALGRIND ERROR IS HERE*/
idNum++;
sprintf(newCatID, "C%04i", idNum);/*NEXT VALGRIND ERROR IS HERE*/
printf("New Category ID: %sn", newCatID);/*NEXT VALGRIND ERROR IS HERE*/
free(temp);
return newCatID;
}
Invalid write of size 1
0 bytes after a block of 4 alloc'd
Invalid read of size 1
0 bytes after a block of 5 alloc'd
Invalid write of size 1
0 bytes after a block of 5 alloc'd
Invalid read of size 1
0 bytes after a block of 5 alloc'd
在此循环的最后一次迭代中:
for(i=1; i<ID_LEN; i++)/*FIRST VALGRIND ERROR IS HERE*/
{
temp[j]= catID[i];
j++;
}
就越界了因为你为
中的LEN - 1
分配了空间temp = malloc(ID_LEN-1);
改变
temp = malloc(ID_LEN);
for(i = 1; i < ID_LEN; i++)
{
temp[j] = catID[i];
j++;
}
/* here you need to add the trailing ' ' */
temp[j] = ' ';