首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >直接使用char数组赋值结构安全吗?

直接使用char数组赋值结构安全吗?
EN

Stack Overflow用户
提问于 2020-04-01 16:42:33
回答 2查看 42关注 0票数 1

我有一个结构体:

代码语言:javascript
复制
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的内存区?

我测试了一下,似乎没什么问题。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2020-04-01 17:22:29

是的,你可以像这样做作业是安全的(它是逐位复制的)

代码语言:javascript
复制
#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;
}

但请看下面的内容

代码语言:javascript
复制
#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“,并导致内存泄漏并再次释放相同的内存,因此,如果您构造包含指针,则需要对此负责,您可以这样做

代码语言:javascript
复制
#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;
}
票数 0
EN

Stack Overflow用户

发布于 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));

为结构分配内存。(不是指针)

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60966822

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档