我有一个结构体:
struct test {
int a;
char b[20];
};
struct test x;
struct test *y = malloc(sizeof(*y));
y->a = 3;
memcpy(y->b, "aaaa", 4);然后如果我赋值x = *y;
和free(y);
安全吗?赋值是否从y->b复制到x->b?或者只是将x->b指向y->b的内存区?
我测试了一下,似乎没什么问题。
发布于 2020-04-01 17:22:29
是的,你可以像这样做作业是安全的(它是逐位复制的)
#include<stdio.h>
#include<string.h>
struct test
{
int a;
char b[20];
};
int main()
{
struct test ob1,ob2;
ob1.a=1;
strcpy(ob1.b,"abc");
ob2=ob1;
printf("%c\n%s",ob2.a,ob2.b);
return 0;
}但请看下面的内容
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct test
{
char *ptr;
};
int main()
{
struct test ob1,ob2;
ob1.ptr=malloc(sizeof(char)*10);
ob2.ptr=malloc(sizeof(char)*10);
if(ob1.ptr==NULL||ob2.ptr==NULL)
{
if(ob1.prt!=NULL)
free(ob1.ptr);
if(ob2.ptr!=NULL)
free(ob2.ptr);
exit(1);
}
strcpy(ob1.ptr,"abc");
ob2=ob1;
strcpy(ob2.ptr,"def");
printf("%s",ob1.ptr);
free(ob1.ptr);
free(ob2.ptr);
return 0;
}这段代码打印"def“,并导致内存泄漏并再次释放相同的内存,因此,如果您构造包含指针,则需要对此负责,您可以这样做
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct test
{
char *ptr;
};
void testcopy(struct test* ob1,struct test* ob2)
{
strcpy(ob1->ptr,ob2->ptr);
}
int main()
{
struct test ob1,ob2;
ob1.ptr=malloc(sizeof(char)*10);
ob2.ptr=malloc(sizeof(char)*10);
if(ob1.ptr==NULL||ob2.ptr==NULL)
{
if(ob1.prt!=NULL)
free(ob1.ptr);
if(ob2.ptr!=NULL)
free(ob2.ptr);
exit(1);
}
strcpy(ob1.ptr,"abc");
testcopy(&ob2,&ob1);
strcpy(ob2.ptr,"def");
printf("%s",ob1.ptr);
printf("\n%s",ob2.ptr);
free(ob1.ptr);
free(ob2.ptr);
return 0;
}发布于 2020-04-01 17:03:44
同样,正如@WhozCraig在评论中提到的那样,它是安全的,你可以在x中复制*y的内容(所以当y改变时,x不会改变)。
与你的问题无关,但我想说,当你使用memcpy时,如果你想将完整的字符串复制到另一个字符串中,你应该使用length of string + 1(复制\0)。例如,在您的代码中,y->b没有终止。
另外,这里应该是struct test *y = malloc(sizeof(*y)); this:
struct test *y = malloc(sizeof(y));
为结构分配内存。(不是指针)
https://stackoverflow.com/questions/60966822
复制相似问题