malloc():即使我检查内存分配函数的结果,内存也会损坏

时间:2017-05-19 02:13:45

标签: c malloc dynamic-memory-allocation

我的项目中有以下代码:

static int* simpleRoute (int* initialRoute, int n, int i, int k) {
    int* newRoute = (int*)malloc(n);
    if (!newRoute) {
        return NULL;
    }
    for (int j = 0; j < i; j++) {
        newRoute[j] = initialRoute[j];
    }
    for (int j = i; j < k+1; j++) {
        newRoute[j] = initialRoute[j];
    }
    for (int j = k+1; j < n; j++) {
        newRoute[j] = initialRoute[j];
    }
    return newRoute;
}

我一直有这个错误:

0 0x7ffff7a43428    __GI_raise(sig=sig@entry=6) (../sysdeps/unix/sysv/linux/raise.c:54)
1 0x7ffff7a4502a    __GI_abort() (abort.c:89)
2 0x7ffff7a857ea    __libc_message(do_abort=2, fmt=fmt@entry=0x7ffff7b9e2e0 "*** Error in `%s': %s: 0x%s ***\n") (../sysdeps/posix/libc_fatal.c:175)
3 ??    0x00007ffff7a8f81e in malloc_printerr (ar_ptr=0x7ffff7dd1b20 <main_arena>, ptr=0x609370, str=0x7ffff7b9b142 "malloc(): memory corruption", action=<optimized out>) (malloc.c:5004)
4 ??    _int_malloc (av=av@entry=0x7ffff7dd1b20 <main_arena>, bytes=bytes@entry=4) (malloc.c:3472)
5 0x7ffff7a915d4    __GI___libc_malloc(bytes=4) (malloc.c:2911)
6 0x40338b  simpleRoute(graphe=0x609580, initialRoute=0x609350, i=6, k=1) 
7 0x403522  opt2Simple(graphe=0x609580)
8 0x404b60  main()

我不确定导致此错误的原因有什么帮助?

1 个答案:

答案 0 :(得分:3)

您分配n个字节,但是您想为n int分配空间。 int(通常)超过一个字节。

malloc(n)更改为malloc(n*sizeof(int))

(另外,(int*)是不必要的)