分段故障11尝试使用的memcpy后得到的数据

问题描述 投票:1回答:1

我遇到了一个问题,当我使用a.out命令来运行我的./a.out文件。我正在分割代码错误号11.试图访问共享内存时,我得到一个分段错误。我用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");
            }
        }

    }
}
c
1个回答
3
投票

    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

© www.soinside.com 2019 - 2024. All rights reserved.