排查了好多遍,知道问题应该是realloc用的不对,但是不知道哪里用错了,求好心高手指点一二~
代码如下:
#define STR_COUNT 5
#define BUF_LEN 50
#define CAR_INCR 3
void sort(char **pStrings,size_t count);
void swap(char **str1,char **str2);
void list_strings(char **pStrings,size_t count);
int main(void)
{
size_t capacity=STR_COUNT;
size_t str_count=0;
char buf[BUF_LEN];
char **pStrings=(char**)calloc(capacity,sizeof(char*));
char **psTemp=NULL;
size_t str_len=0;
//Read all strings
printf(“Enter some strings and end by entering an empty line:\n”);
while(true)
{
if(!fgets(buf,sizeof(buf),stdin))
{
printf(“Error on reading strings.\n”);
free(pStrings);
pStrings=NULL;
return 1;
}
if(buf[0]==”\n”)
break;
if(capacity==str_count)
{
capacity+=3;
psTemp=(char**)realloc(pStrings,capacity*sizeof(char*));
if(!psTemp)
{
printf(“Reallocation failed.\n”);
return 2;
}
pStrings=psTemp;
}
str_len=strnlen_s(buf,BUF_LEN)+1;
if(!(pStrings[str_count]=(char*)malloc(sizeof(char)*str_len)))
{
printf(“Allocation for strings failed.\n”);
return 3;
}
strcat_s(pStrings[str_count++],str_len,buf);
printf(“str_count=%d\n”,str_count);
}
for(size_t i=0;i<str_count;i++)
{
printf(“str_count=%d %s”,i,pStrings[i]);
free(pStrings[i]);
pStrings[i]=NULL;
}
return 0;
}
代码如下:
#define STR_COUNT 5
#define BUF_LEN 50
#define CAR_INCR 3
void sort(char **pStrings,size_t count);
void swap(char **str1,char **str2);
void list_strings(char **pStrings,size_t count);
int main(void)
{
size_t capacity=STR_COUNT;
size_t str_count=0;
char buf[BUF_LEN];
char **pStrings=(char**)calloc(capacity,sizeof(char*));
char **psTemp=NULL;
size_t str_len=0;
//Read all strings
printf(“Enter some strings and end by entering an empty line:\n”);
while(true)
{
if(!fgets(buf,sizeof(buf),stdin))
{
printf(“Error on reading strings.\n”);
free(pStrings);
pStrings=NULL;
return 1;
}
if(buf[0]==”\n”)
break;
if(capacity==str_count)
{
capacity+=3;
psTemp=(char**)realloc(pStrings,capacity*sizeof(char*));
if(!psTemp)
{
printf(“Reallocation failed.\n”);
return 2;
}
pStrings=psTemp;
}
str_len=strnlen_s(buf,BUF_LEN)+1;
if(!(pStrings[str_count]=(char*)malloc(sizeof(char)*str_len)))
{
printf(“Allocation for strings failed.\n”);
return 3;
}
strcat_s(pStrings[str_count++],str_len,buf);
printf(“str_count=%d\n”,str_count);
}
for(size_t i=0;i<str_count;i++)
{
printf(“str_count=%d %s”,i,pStrings[i]);
free(pStrings[i]);
pStrings[i]=NULL;
}
return 0;
}
解决方案
60
strcat_s(pStrings[str_count++],str_len,buf);
改成:
strcat_s(pStrings[str_count++],BUF_LEN,buf);
改成:
strcat_s(pStrings[str_count++],BUF_LEN,buf);
60
另外,你应该用strcpy_s 而不是strcat_s吧