繁体   English   中英

直接使用 char 数组分配结构是否安全?

[英]Is assigning a struct with char array directly safe?

我有一个结构:

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的内存区域?

我测试了,好像没有出现问题。

也正如@WhozCraig 在评论中提到的那样,它是安全的,并且您正在复制x*y内容(因此当y更改时x不会)。

与您的问题无关,但我想说的是,当您使用memcpy如果要将完整的字符串复制到另一个字符串中,您应该使用length of string + 1 (复制\\0 )。 例如,在您的代码中y->b不会终止。

也在这里这应该是struct test *y = malloc(sizeof(*y)); 这个:

struct test *y = malloc(sizeof(y));

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

是的,你可以像这样进行分配是安全的(它是一点一点的复制)

#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;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM