0

My teacher gave us a piece of code as homework and asked us what is the kind of error.

I don't really know what errors exist so that's why I'm asking here.

#include <stdio.h>

int main()
{
    int m, n;
    scanf("%d%d", &m, &n);
    int i, ** a;
    a = (int**)malloc(m * sizeof(int*));
    for (i = 0; i < m; i++)
    {
        a[i] = (int*)malloc(n * sizeof(int));
    }
    free(a[0]);
    free(a);
    return 0;
}

It is either a runtime error, a memory leak, or a linkedit error.

Can anybody help me classify this error and also help me understand the difference between these types of errors?

Thanks.

  • To begin with you're not checking the return value from `scanf()` so you have no idea what's actually in `m` and `n` when you try to allocate your multiple one-dimensional arrays. You can easily get a run-time error from that. And then, to not have a memory leak, every `malloc()` call needs a corresponding `free()` call (as a first-order comment...). – Andrew Henle Feb 01 '21 at 15:29
  • So what error is that? –  Feb 01 '21 at 15:31
  • 3
    to use `malloc` and `free`, you need to include `stdlib.h` – koder Feb 01 '21 at 15:31
  • Hint: look what you allocate vs. what you free. Are you sure all memory allocated is eventually freed? – Jabberwocky Feb 01 '21 at 15:35

1 Answers1

1

It is a memory leak for any m > 1. To avoid it you need to free all "malloced" memory.

In your code first is allocated space for m pointers to int. Then it allocates m memory blocks having the size of n integers.

You free only 2 memory blocks. The second return frees the memory where pointers to allocated blocks are kept. Access to them is lost and this memory cannot be accessed to freed anymore - thus "memory leak"

BTW if it is the code given by the teacher then it shows that he needs to start to read SO to learn some stuff about the C language (or even better read an up to date book about this language).

  1. main What are the valid signatures for C's main() function?
  2. he should check the return value of scanf. He should check if the scanned values make any sense.
  3. He should use the correct type for sizes and indexes it is size_t
  4. He should not cast the result of malloc
  5. He should use objects instead of types in sizeof
  6. He does not include stdlib.h required to use malloc & free.

Quite a lot issues in the 10 lines C programm.

0___________
  • 60,014
  • 4
  • 34
  • 74
  • Thanks a lot for your answer. ^the code was intentionally written with errors by my teacher, by the way. The homework was to decide which errors will happen. –  Feb 01 '21 at 15:52
  • @OctavianNiculescu put all the errors from this answer in your homework you'll get an A+ mark. – Jabberwocky Feb 01 '21 at 15:53
  • It was like an extra homework, it won't be marked. I just wanted to learn more :) –  Feb 01 '21 at 15:53