我试图实现一个简单的函数,它可以连接传递给它的任意数量的字符串。我调用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;
}发布于 2012-02-01 16:51:32
您的代码具有未定义的行为。标准要求传递给realloc的指针应该与使用内存管理函数分配的动态内存的指针完全匹配。该标准规定的内存管理功能包括:
aligned_alloc、calloc、malloc和realloc。
您传递给realloc()的指针没有由这些函数返回,因此出现了未定义的行为。
参考资料:
realloc c99标准: 7.22.3.5 函数
简介: #1
#include <stdlib.h>
void *realloc(void *ptr, size_t size);#3
如果ptr为空指针,则realloc函数的行为与指定大小的malloc函数类似。否则,如果ptr与先前由内存管理函数返回的指针不匹配,或者如果通过调用或realloc函数释放了空间,则行为为未定义的。如果无法为新对象分配内存,则不会释放旧对象,并且其值保持不变。
发布于 2012-02-01 16:49:24
将字符串文字传递给mstrcat函数,它们可能存储在进程的只读区域中,这意味着它们不能被修改或调整大小。
realloc只能与以前由malloc或realloc返回的指针一起使用。其他类型的使用(就像您的一样)会产生未定义的行为。
发布于 2012-02-01 16:54:03
mstrcat函数以s开始,指向第一个参数。然后,您将尝试realloc()该指针,它是一个静态字符串。这是行不通的。您只能重新锁定先前由malloc()分配的指针。
我建议您将char *s=first更改为char *s=strdup(first),以分配第一个参数的副本,然后此代码就可以工作了。
连接算法效率很低,但那是另一回事了……(提示:您可能希望枚举参数并跟踪总大小,然后分配相应的缓冲区,然后将所有参数连接到其中)
https://stackoverflow.com/questions/9092986
复制相似问题