使用~8MB缓冲区写入时出现SEGFULT()(OSX,Linux)

使用~8MB缓冲区写入时出现SEGFULT()(OSX,Linux),linux,segmentation-fault,bsd,Linux,Segmentation Fault,Bsd,我很好奇在Linux/OSX/FreeBSD上write()和read()可以处理什么样的缓冲区大小,所以我开始使用下面这样的愚蠢程序: #include <unistd.h> #include <fcntl.h> #include <stdio.h> #include <string.h> #include <sys/stat.h> int main( void ) { size_t s = 8*1024*1024 - 16

我很好奇在Linux/OSX/FreeBSD上write()和read()可以处理什么样的缓冲区大小,所以我开始使用下面这样的愚蠢程序:

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

int main( void ) {
    size_t s = 8*1024*1024 - 16*1024;
    while( 1 ) {
        s += 1024;
        int f = open( "test.txt", O_CREAT | O_WRONLY | O_TRUNC, S_IRUSR | S_IWUSR | S_IXUSR );
        char mem[s];
        size_t written = write( f, &mem[0], s );
        close( f );
        printf( "(%ld) %lu\n", sizeof(size_t), written );
    }
    return 0;
}
这在OSX和Linux上是一样的,但是我的FreeBSD虚拟机不仅运行这个测试快得多,而且还可以在很多方面继续运行!我已经成功地测试了511MB的内存,这是一次调用中要写入的数据量

是什么导致write()调用segfault,我如何计算出在一次调用中可以写入()的最大数量,而不做像我现在这样荒谬的事情

(注意,这三个操作系统都是64位的,OSX 10.7.3,Ubuntu 11.10,FreeBSD 9.0)

故障不在
write()
之内,它是堆栈溢出。试试这个:

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

int main( void )
{
    void *mem;
    size_t s = 512*1024*1024 - 16*1024;
    while( 1 )
    {
        s += 1024;
        int f = open( "test.txt", O_CREAT | O_WRONLY | O_TRUNC, S_IRUSR | S_IWUSR | S_IXUSR );
        mem = malloc(s);
        size_t written = write( f, mem, s );
        free(mem);
        close( f );
        printf( "(%ld) %lu\n", sizeof(size_t), written );
    }
    return 0;
}
#包括
#包括
#包括
#包括
#包括
#包括
内部主(空)
{
void*mem;
大小s=512*1024*1024-16*1024;
而(1)
{
s+=1024;
int f=open(“test.txt”,O|u CREAT | O|u WRONLY | O|u TRUNC,S|u IRUSR | S|u IWUSR | S|IXUSR);
mem=malloc(s);
写入的大小=写入(f,mem,s);
免费(mem);
关闭(f);
printf((%ld)%lu\n),sizeof(size\u t),书面形式;
}
返回0;
}

唉,我真的应该意识到这一点。我想了想,然后很快就忘了在编译之前思考。谢谢大家!@staticfloat我试图用
strace
gdb
证明这是堆栈溢出,但我做不到-也许有人可以建议如何确定堆栈溢出是故障的原因。如果您想知道,这确实解决了问题。:)
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <sys/stat.h>

int main( void )
{
    void *mem;
    size_t s = 512*1024*1024 - 16*1024;
    while( 1 )
    {
        s += 1024;
        int f = open( "test.txt", O_CREAT | O_WRONLY | O_TRUNC, S_IRUSR | S_IWUSR | S_IXUSR );
        mem = malloc(s);
        size_t written = write( f, mem, s );
        free(mem);
        close( f );
        printf( "(%ld) %lu\n", sizeof(size_t), written );
    }
    return 0;
}