Meryem
Meryem

Reputation: 487

malloc() : memory corruption even if i check result of memory allocation function

I have the following code in my project:

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;
}

I keep having this error:

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

I'm not sure what cause this error, any help?

Upvotes: 1

Views: 993

Answers (1)

You allocate n bytes but you want to allocate space for n ints. An int is (usually) more than one byte.

Change malloc(n) to malloc(n*sizeof(int)).

(Also, (int*) is unnecessary)

Upvotes: 3

Related Questions