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

落花浮王杯 提交于 2019-12-02 06:06:18

问题


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 :-)



来源:https://stackoverflow.com/questions/51392694/memcpy-and-then-printf-calling-stat-writing-in-buffer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!