红联Linux门户
Linux帮助

Linux内存写入问题

发布时间:2010-11-05 10:00:21来源:红联作者:Jesse1014
我申请一段动态内存,在while循环中使用memcpy写入数据,第一次写入正常,当执行while循环,第二次写入时,Linux系统终止了我的进程;我查了一下这方面的原因,可能是因为Linux系统为了防止滥用内存,所以直接终止了我的进程。也就是说我对内存的操作是系统所不能容忍的,那我应该怎么样进行内存的数据写入呢?有谁遇到过类似问题吗?请教各位!
文章评论

共有 2 条评论

  1. deepwhite 于 2010-11-05 12:08:59发表:

    引用:
    可能是因为Linux系统为了防止滥用内存,所以直接终止了我的进程。
    Jesse1014 发表于 2010-11-5 10:00


    内核没有办法、也不应该去控制用户对内存的使用,不管是浪费还是滥用,只要别动内核自己 reserved 的内存空间就没事。所以你的猜测,应该是错误的。

  2. deepwhite 于 2010-11-05 11:37:11发表:

    [i=s] 本帖最后由 deepwhite 于 2010-11-5 12:01 编辑 [/i]

    我做了个简单的试验,没发现问题啊。[code]
    /* test.c */
    #include
    #include
    #include
    #include


    char *get_rand_char(int count)
    {
    char *buf = NULL;
    char c;
    int i, val;
    unsigned int seed;
    if (count < 0)
    count = 1;
    buf = (char *)malloc(count+1);
    if (buf == NULL) {
    fprintf(stderr, "ERROR: Failed to alloc memory for string.\n");
    return NULL;
    }
    memset(buf, 0, count+1);
    seed = time(NULL);
    srand(seed);
    for (i = 0; i < count; i++) {
    val = rand();
    c = val%93 + 33;
    *(buf + i) = c;
    }
    return buf;
    }

    int main(int argc, char **argv)
    {
    int ret, idx;
    char *rd_chr = NULL;
    char *buf = malloc(64);
    if (!buf) {
    fprintf(stderr, "ERROR: Failed to alloc memory.\n");
    return -1;
    }
    for (idx = 0; idx < 10; idx++) {
    rd_chr = get_rand_char(63);
    if (rd_chr == NULL) {
    fprintf(stderr, "ERROR: Failed to get random string!\n");
    return -1;
    }
    printf ("src: %s\n", rd_chr);
    memcpy(buf, rd_chr, 64);
    printf ("dst: %s\n", buf);
    printf ("%s\n", (!strcmp(buf, rd_chr))?"Same":"Different");
    free(rd_chr);
    }
    return 0;
    }
    [/code]测试:[code]
    deepwhite@localhost tmp $ make test
    cc test.c -o test
    deepwhite@localhost tmp $ ./test
    src: ==#eV30ACWP&0m"Vdst: ==#eV30ACWP&0m"VSame
    src: ==#eV30ACWP&0m"Vdst: ==#eV30ACWP&0m"VSame
    src: ==#eV30ACWP&0m"Vdst: ==#eV30ACWP&0m"VSame
    src: ==#eV30ACWP&0m"Vdst: ==#eV30ACWP&0m"VSame
    src: ==#eV30ACWP&0m"Vdst: ==#eV30ACWP&0m"VSame
    src: ==#eV30ACWP&0m"Vdst: ==#eV30ACWP&0m"VSame
    src: ==#eV30ACWP&0m"Vdst: ==#eV30ACWP&0m"VSame
    src: ==#eV30ACWP&0m"Vdst: ==#eV30ACWP&0m"VSame
    src: ==#eV30ACWP&0m"Vdst: ==#eV30ACWP&0m"VSame
    src: ==#eV30ACWP&0m"Vdst: ==#eV30ACWP&0m"VSame
    [/code]

    方便的话可以把你的代码贴出来看看。