c - is there any consequence if I do assignment but not memcpy after malloc -
in following program:
int main() { struct node node; struct node* p = (struct node*) malloc(sizeof(struct node)); *p =node; printf("%d\n", *p->seq); }
usually did memcpy(p, node, sizeof(node))
now tried code above, , works fine, i'm afraid there consequence or faulty stuff if assignment not memcpy
after malloc
. there or assignment correct? thanks!
jesus ramos correct:
1) *p =node;
copies in "node" "*p"
2) not need extraneous "memcpy()"
3) must allocate "*p" (with "malloc()") before copy.
here standalone test:
// c source #include <stdio.h> #include <malloc.h> struct node { int a; int b; struct node *next; }; int main() { struct node node; struct node *p = malloc(sizeof(struct node)); *p = node; return 0; } # resulting assembler main: leal 4(%esp), %ecx andl $-16, %esp pushl -4(%ecx) pushl %ebp movl %esp, %ebp pushl %ecx subl $20, %esp movl $12, (%esp) call malloc movl %eax, -8(%ebp) movl -8(%ebp), %edx movl -20(%ebp), %eax movl %eax, (%edx) movl -16(%ebp), %eax movl %eax, 4(%edx) movl -12(%ebp), %eax movl %eax, 8(%edx) movl $0, %eax addl $20, %esp popl %ecx popl %ebp leal -4(%ecx), %esp ret
Comments
Post a Comment