程序效率,读写都分配内存

Program efficiency, allocate memory for both read and write

我写了一个简单的程序,我想知道我是否以高效的方式编写了该程序。程序打开一个文件进行读写,然后用pwrite写入(我不希望文件的偏移量随着写入而移动),然后用pread读取文件。我只是想知道是否有必要像我一样分配两次内存。

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

int main(int argc, char const *argv[])
{
    char *write_buf = malloc(14), *read_buf = malloc(14);

    int fd = open("file", O_CREAT | O_RDWR, 0644); /* open a file called file */
    if (fd == -1) {
         perror("write");
         exit(-1); // Error, exit program
    }

    strcpy(write_buf, "Hello, World!"); /* copy string into write_buf */
    pwrite(fd, write_buf, strlen(write_buf), 0); /* pwrite (without moving file pointer) write_buf into fd (file) */
    pread(fd, read_buf, strlen(write_buf), 0); /* pread (without moving file pointer) into read_buf from fd (file) */

    close(fd);
    free(write_buf); free(read_buf);

    return 0;
}

这里有很多问题,只是有点不对劲,但在 C 中,有点不对劲是工作正常和一直崩溃之间的区别。清理结果如下:

int main(int argc, char const *argv[])
{
  const int BUFFER_SIZE = 1024;
  char *buf = malloc(BUFFER_SIZE);

  int fd = open("file", O_CREAT | O_RDWR, 0644);

  if (fd == -1) {
    perror("write");
    exit(-1);
  }

  // Here strncpy() can fail if the buffer is too small, so ensure
  // your buffer size is big enough for any reasonable cases. Test the
  // return value if you're not sure what the input size is going to be.
  strncpy(buf, "Hello, World!", BUFFER_SIZE);
  pwrite(fd, buf, strlen(buf), 0);
  
  // strlen() is the wrong tool here, you need the size of the buffer
  // itself, not the length of whatever's in it.
  pread(fd, buf, BUFFER_SIZE, 0);

  close(fd);

  // This wouldn't be necesssary if you had: char buf[BUFFER_SIZE]
  free(buf);

  return 0;
}

了解 strlen()sizeof 之间的区别,以及如何在代码中始终如一地使用常量大小。

这里的原则是你想改变一件事并让它正确地影响你的代码。