我试图实现一个简单的函数,可以连接任何数量的字符串传递给它。我对realloc的调用失败。是否这样做是因为我传递给函数的字符串参数存储在数据段中,realloc看起来是从堆中分配内存的?这只是我的一个想法。我是初学者,所以请原谅,如果它似乎愚蠢。我如何使这个功能运行?realloc()失败
//Program to implement a function that can concatenate any number of argumnets
#include<stdio.h>
#include<stdarg.h>
#include<string.h>
#include<stdlib.h>
char *mstrcat(char *first, ...);
int main(int argc, int **argv){
char *s;
s=mstrcat("I ","Love ","Stack","Overflow");
printf("%s\n",s);
}
char *mstrcat(char *first, ...){
char *s=first,*p;
int len=0; // stores the length of the string as it grows
len=strlen(s);
va_list aptr; // creates a pointer to the unnamed argument list
va_start(aptr,first); // initialise aptr to the first unnamed argument
if(aptr==NULL){
return s;
}
while((p=va_arg(aptr,char *))!=NULL){ // till there are no more arguments to process
len+=strlen(p);
if((s=(char *)realloc(s,len+1))!=NULL){
strcat(s,p);
}
else{
printf("Failed to concatenate\n");
return first;
}
}
return s;
}
您没有将NULL作为mstrcat的最终参数传递给此处。这会导致你的循环读取垃圾数据。这真的是你正在使用的测试案例吗?如果不是,我们能否看到真正的测试案例? – templatetypedef 2012-02-01 08:49:49
您是通过malloc()或公司分配给mstrcat()的字符串吗?否则你不能对它们做一个realloc()。正如[here](http://linux.die.net/man/3/realloc)所述:*除非ptr为NULL,否则它必须早先通过调用malloc(),calloc()或realloc() 。* – m0skit0 2012-02-01 08:53:28
@templatetypedef我添加了'NULL'和下面的代码行,它工作正常。 'len = strlen(first);''s =(char *)malloc(len + 1);''strcpy(s,first);'。谢谢你的帮助。 – Bazooka 2012-02-01 09:41:23