【问题标题】:malloc() : memory corruption even if i check result of memory allocation functionmalloc() :即使我检查内存分配函数的结果,内存也会损坏
【发布时间】:2017-05-19 02:13:44
【问题描述】:

我的项目中有以下代码:

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

我不确定是什么导致了这个错误,有什么帮助吗?

【问题讨论】:

  • 与问题无关,但我只是进行了一个标签编辑,这与另一个同时编辑代码示例的同时编辑一致(〜同一秒左右)并合并了编辑。我可以确认@Meryem 进行了代码编辑吗?
  • 你写的越界 - 你 malloc n 字节,但你写到 n 整数到空间。一个int占用超过1个字节
  • int* newRoute = (int*)malloc(n); 要求 nsizeof (int) 的倍数。将其更改为int* newRoute = malloc(n * sizeof (int)); 并且无需强制转换malloc。
  • 什么是n?它必须是 sizeof(int) 的倍数才能使代码正常工作。如果n 应该是最大索引,则代码应该是int *newRoute = malloc(n*sizeof(*newRoute))
  • valgrind 是你有记忆问题的朋友

标签: c malloc dynamic-memory-allocation


【解决方案1】:

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

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

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

【讨论】:

  • 我已经尝试过了,但我仍然得到同样的错误,我在我的代码的另一部分中只使用了(int*)malloc(n); 另一个变量,它工作得很好,我只是这部分有问题
  • @Meryem 那么你的代码的其他部分也是错误的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-04
相关资源
最近更新 更多