c - 使用 memcpy 后尝试获取数据的段错误 11

标签 c

当我使用 ./a.out 命令运行我的 a.out 文件时遇到问题。我收到分段代码错误号 11。我在尝试访问 sharedMemory 时收到段错误。我使用 memcpy 将数据粘贴到共享内存中。是段错误 11。

我是否正确地访问了内存?

#include<stdio.h>
#include<sys/types.h>
#include<sys/shm.h>
#include<sys/ipc.h>
#include<unistd.h>
#include<time.h>
int main(){
    pid_t childPid;
    childPid = fork();
    char *shm;
    if(childPid == 0){
        char *args[] ={"ls","-l",NULL};
        int shmid;
        int shsize = 100;
        key_t key;
        char *s;
        key = 9876;
        shmid = shmget(key,shsize, IPC_CREAT | 0666);
        if(shmid < 0){
            printf("error getting shmid");
            exit(1);
        }

        shm = shmat(shmid,NULL,0);
        if(shm == (char *) -1){
            printf("error getting shared memory");
            exit(1);
        }
        time_t startTime;
        gettimeofday(&startTime,0);
        memcpy(shm,&startTime,sizeof(startTime));
        time_t endTime;
        execvp(args[0],args);
        printf("successfuly created child proceess");
        exit(0);
    }

    else if (childPid <0){
        printf("unsuccessfuly created child proccess");



        else{
            int returnStatus;
            waitpid(childPid,&returnStatus,0);
            if(returnStatus == 0){
                printf("The child terminated normally");
                printf("%s",*shm);
            }

            if(returnStatus == 1){

                printf("The child terminated with error");
            }
        }

    }
}

最佳答案

    time_t startTime;
    gettimeofday(&startTime,0);

gettimeofday 的第一个参数必须是 struct timeval * 而不是 time_t *

所以

    struct timeval startTime;
    gettimeofday(&startTime,0);

char *shm;
...
printf("%s",*shm);

你不能解引用shm,因为目前它的第一个字符的ascii码被用作字符串的地址,必须是

char *shm;
...
printf("%s",shm);

之后

else if (childPid <0){
    printf("unsuccessfuly created child proccess");

丢失


我鼓励您编译时要求编译器产生警告,gcc 使用选项 -pedantic -Wall

关于c - 使用 memcpy 后尝试获取数据的段错误 11,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54537686/

相关文章:

c - 如何删除c中文本文件中的最后一个字符?

c - Else 语句在 strcmp 中返回错误结果(比较哈希值)(已更新)

c - 将低字节从 int 复制到 char : Simpler to just do a byte load? 的指令

c - C 中的 "Error: array subscript is not an integer"带指针

c - 以邻接矩阵作为参数的 Prim MST

c++ - 从文件读取并将值放入结构数组时遇到问题

c++ - 共享内存执行得这么快?

c++ - 守护进程多线程服务器

c++ - 关于dup2和多线程的问题

c - 在一个声明中不声明多个变量是否会使代码更具可读性?