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



我的项目中有以下代码:

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()

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

您分配了n字节,但您希望为n int分配空间。一个int(通常(超过一个字节。

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

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

相关内容

  • 没有找到相关文章

最新更新