发出重新分配内存到字符串的问题
C的新手并试图学习。 在这里,我尝试创建一个函数,该函数使用动态内存分配和ByRef复制字符串直至第一个空间。 似乎我在使用Realloc的方式做错了。您能帮我弄清楚我使用动态内存分配的方式有什么问题?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void f1(char **c, char *s);
int main() {
char * s = "this is an example";
char *c;
c =(char *) malloc(sizeof(char));
f1(&c,s);
free(c);
}
void f1(char **c, char *s)
{
int i=0;
while ((s[i])!=' ')
{
(*c)[i]=s[i];
i++;
(*c)=(char *)realloc ((*c),sizeof(char)*i);
}
(*c)[i]='\0';
printf("\n%s\n",*c);
}
New to c and trying to learn.
Here I tried to create a function that copies a string until first space using dynamic memory allocation and byref.
Seems like I'm doing something wrong with the way I used realloc. Can you help me figure out what is wrong with the way I used dynamic memory allocation?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void f1(char **c, char *s);
int main() {
char * s = "this is an example";
char *c;
c =(char *) malloc(sizeof(char));
f1(&c,s);
free(c);
}
void f1(char **c, char *s)
{
int i=0;
while ((s[i])!=' ')
{
(*c)[i]=s[i];
i++;
(*c)=(char *)realloc ((*c),sizeof(char)*i);
}
(*c)[i]='\0';
printf("\n%s\n",*c);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
已经为一个字符分配了一个字符的内存
的第一次迭代中,
在函数调用之前,在填充此内存
,然后再次分配了一个字符的内存,
因为在循环的第一次迭代中>变得等于
1
。因此,在循环的第二次迭代中,试图在分配的内存之外写作,从而导致不确定的行为。您至少需要写作,
也需要更安全地使用中间指针作为例如,
但是在这种情况下,您还需要更改功能逻辑。
一样更改功能
,并且应该更改程序的状况
并且应该像使用您的方法
。然而,程序输出是
一种具有许多内存重新分配的方法,效率低下。
我会以以下方式编写
程序输出是
Before the function call there was already allocated memory for one character
In the first iteration of the while loop
this memory was filled
and then again there was allocated memory only for one character
because in the first iteration of the loop
i
becomes equal to1
. So in the second iteration of the loop there is an attempt to write outside the allocated memory that results in undefined behavior.You need to write at least like
Also it will be more safer to use an intermediate pointer as for example
but in this case you will need also to change the function logic.
And the function should be declared like
and the condition of the should be changed like
Using your approach the program can look the following way.
The program output is
However such an approach with many memory reallocations is inefficient.
I would write the program the following way
Again the program output is
正如@unholysheep提到的那样,我用来分配内存的
i
太小。更改为(*t)=(char*)realloc(((*t),(i+1)*sizeof(char));
,并且起作用。As @UnholySheep mentioned the
i
I used to allocate memory was too small. Changed to(*t) = (char *)realloc((*t),(i+1)*sizeof(char));
and it worked.