strcpy是以'\0'判断结尾的,而memcpy不存在'\0'结尾的问题,它拷贝的是内存地址。(strcmp和memcmp同理)
今天遇到的问题是memcpy,strncpy,snprintf指定拷贝的长度问题。比如字符串"abc",我指定的长度如果是3就会有结尾的问题产生,但是我指定4就一定会在"abc"的末尾跟上'\0'然后放入目的地址中吗?不一定
通常是自动在结尾加上'\0',在mmap写读文件的时候就不会。通常的办法是:
memcpy(buf,srcbuf,sizeof(buf));
buf[strlen(srcbuf)]=0;
|
Mmap时会出错情况程序示例。mapShareWr.c
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
typedef struct {
char name[4];
int age;
} people;
int main(int argc, char **argv)
{
int fd, i;
people *p_map;
char temp;
fd = open(argv[1], O_CREAT | O_RDWR | O_TRUNC, 0777);
lseek(fd, sizeof(people) * 5 - 1, SEEK_SET);
write(fd, "", 1);
p_map = (people*)mmap(NULL, sizeof(people)*10, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
close(fd);
temp = 'a';
for (i = 0; i < 10; i++) {
temp += 1;
memcpy( ( *(p_map+i) ).name, &temp, 4);
(*(p_map+i) ).name[1] = '\0';
(*(p_map+i) ).age = 20+i;
}
printf("Initialize over \n");
sleep(5);
munmap(p_map, sizeof(people) * 10);
printf("unmap OK \n");
return 0;
}
|
mapShareRe.c
#include <stdio.h>
#include <sys/mman.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
typedef struct {
char name[4];
int age;
} people;
int main(int argc, char **argv)
{
int fd, i;
people *p_map;
fd = open(argv[1], O_CREAT | O_RDWR, 0777);
p_map = (people*)mmap(NULL, sizeof(people)*10, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
for (i = 0; i < 10; i++) {
printf( "name: %s age: %d\n", (*(p_map+i) ).name, (*(p_map+i) ).age );
}
munmap(p_map, sizeof(people) * 10);
close(fd);
return 0;
}
|
gcc mapShareRe.c -o re
gcc mapShareWr.c -o wr
./wr share
./re share
wr程序执行中读,和执行后读的结果是不同的,可是如果没有
(*(p_map+i) ).name[1] = '\0';
就会出问题。
参考链接:
我没有在Linux/FreeBSD下面找到strlcpy
阅读(1764) | 评论(0) | 转发(0) |