memcpy and then printf, calling stat(), writing in

2020-04-13 18:30发布

问题:

here are includes and my function:

I'm trying to copy stbuf->st_mode in buffer with memcpy and when reading it back, value is not what I was trying to copy.

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <string.h>

void r1_getattr(char* pth, int cfd){
    struct stat* stbuf = malloc(sizeof(stat));

    int res = stat(pth, stbuf);

    printf("(%3o)\n", (stbuf->st_mode)&0777);
    char* wbuf = malloc(256);

    memcpy(wbuf, &(stbuf->st_mode), sizeof(mode_t));
    printf("(%3o)\n", (*(mode_t*)((char*)wbuf))&0777);
}

outputs: "(775)" and "( 21)" shouldn't they be the same?

回答1:

Simple typing error:

Replace

struct stat *stbuf = malloc(sizeof(stat));

with

struct stat *stbuf = malloc(sizeof(struct stat));

Always funny to see the weird results we get when we use un-initialized memory :-)