1

I get "corrupted size vs prev_size" error whenever I allocate a dynamic memory in a thread. Whenever I allocate the memory in main() it works fine. But allocating dynamic memory in thread produces the error.

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

void *fib(void *p);
struct mystruct
{
    int *array;
    int size;
};

int main(int argc, char *argv[])
{
    pthread_t tid;
    pthread_attr_t attr;
    pthread_attr_init(&attr);
    struct mystruct obj;

    obj.size = atoi(argv[1]);;

    pthread_create(&tid, &attr, fib, (void *)&obj);
    pthread_join(tid, NULL);
}

void *fib (void *p)
{
    struct mystruct *x = (struct mystruct *)p;
    x->array = (int *) malloc (x->size);

    for (int i=0; i<x->size; i++){
        x->array[i] = i;
        printf("The array is = %d\n", x->array[i]);
    }   
}

I've added snapshot for details.

error saying corrupted size vs prev_size

Thanks!

Hassaan Ahmad
  • 29
  • 1
  • 1
  • 8
  • 5
    The size passed to [`malloc`](http://en.cppreference.com/w/c/memory/malloc) is the size *in bytes*. Not the number of "elements" (which is impossible since `malloc` doesn't know what you're actually allocating memory for). – Some programmer dude Jun 11 '18 at 12:41
  • `(int *) malloc (x->size)` --> `malloc (sizeof *(x->array) * x->size)` – chux - Reinstate Monica Jun 11 '18 at 13:37
  • 4
    For future questions please do not add screenshots of plain text. You can simply copy&paste that text into your question. – Gerhardh Jun 11 '18 at 13:46
  • before accessing beyond `argv[0]`, always check `argc` to assure the command line parameter was actually entered by the user. – user3629249 Jun 11 '18 at 14:07

2 Answers2

5

Try with the following line:

x->array =  malloc (x->size*sizeof(int));

You need to allocate space for x->size integers. malloc accepts as parameter the number of bytes you need. And for n int you need n times the size in bytes of a single int.

Do not forget to return from the main.

Davide Spataro
  • 7,319
  • 1
  • 24
  • 36
  • in C, the heap memory allocation functions: `malloc` `calloc` `realloc` have a return type of `void*` which can be assigned to an pointer. Casting just clutters the code, making it more difficult to understand, debug, etc. – user3629249 Jun 11 '18 at 14:02
  • "Do not forget to return from the main. " I take it you actually mean "do not forget to return the thread status to main"? – Lundin Jun 11 '18 at 14:12
0

I had the same issue and I solved by using an "aligned" version of malloc, i.e.: allocated memory will be aligned. I used this answer https://stackoverflow.com/a/1920516/2155258.

olmanqj
  • 3
  • 3
  • The issue in OP's code is not really about alignment, it's about requesting an incorrectly *sized* memory block. Not also that the `malloc` does some alignment: *If allocation succeeds, returns a pointer that is suitably aligned for any object type with fundamental alignment.* – Adrian Mole Mar 28 '23 at 08:35