Subject: memcpy segfaults
To: None <>
From: Mike Cheponis <mac@Wireless.Com>
List: current-users
Date: 02/03/2000 22:51:08
I'm trying a simple program on 1.4P to mmap() some files and do a copy.
The code is below.  gdb says:

Program received signal SIGSEGV, Segmentation fault.
0x480cba66 in memcpy ()

It's invoked like this:  copyfile copyfile.c foo.c
(thus, trying to copy itself)

This program also seg faults on RH linux gcc

It works fine on bsd/os 4.01 with gcc

I'm probably doing something stupid.

Thanks as usual for help!  -Mike

 * copyfile.c from unix system programming

#include <stdio.h>
#include <sys/mman.h>
#include <fcntl.h>

main(int argc, char **argv){
  int input, output;
  size_t filesize;
  void *source, *target;
  char endchar = '\0';

  /* Check that the correct # of parameters have been passed */
  if(argc != 3){
    fprintf(stderr,"usage: copyfile source target\n");

  /* Open both files */
  if( (input = open(argv[1], O_RDONLY)) == -1){
    fprintf(stderr, "Error opening input file %s\n", argv[1]);

  if( (output = open(argv[2], O_RDWR | O_CREAT | O_TRUNC, 0666)) == -1){
    fprintf(stderr, "Error opening output file %s\n", argv[2]);
  }/* Note that the input file is automatically closed when exiting */

  /*Create 2nd file as same size as first file */
  filesize = lseek(input, 0, SEEK_END);
  lseek(output, filesize-1, SEEK_SET);
  write(output, &endchar, 1);

  /* memory map both input and output files */
  if( (source = mmap(0, filesize, PROT_READ, MAP_SHARED, input, 0)) ==
                                                              (void *)-1){
    fprintf(stderr,"Error mapping input file %s\n", argv[1]);

  if( (target = mmap(0, filesize, PROT_WRITE, MAP_SHARED, output, 0)) ==
                                                              (void *)-1){
    fprintf(stderr,"Error mapping output file %s\n", argv[2]);

  /* copy */
  memcpy(target, source, filesize);

  /* Unmap files */

  munmap(source, filesize);
  munmap(target, filesize);

  exit(0);/* both files will be closed upon exit automatically by OS */