Skip to content
Advertisement

can you guys help me to debug a simple c program with gcc and make it work? (student problems..) [closed]

Hello guys so my question is can you help me to debug a simple c program with gcc and make it work?

The teacher gave me this code and I should debug it and make it work, i tried but without any help I can’t do It.

I compiled it with g++ -g double_free.c -o double_free

The program crashes.

this is the code:

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

#define ARRAY_SIZE 100000
int main(int argc, char* argv[])
{
        int i, test=5;
        int* buf = new int[100000];
        for (i=0; i< ARRAY_SIZE; i++){
               buf[i] = i;
       }
       int result = 0;
       delete []buf;

       printf("result: %dn", result);
       delete[] buf;
       printf("test %dn", test);
       return 0;
}

enter image description here

Advertisement

Answer

Here’s a laundry list of complaints I have about this code:

  • You delete buf twice. This is really the only item I can see that needs actual debugging. The fact that the name of the exercise is double_free is a dead giveaway to experienced coders that this is the issue.

On top of that:

  • You should either be a C coder or a C++ coder, not a C+ coder (that strange variant that doesn’t appear to have fully made the transition). Other than code meant to compile in both C and C++ environments, there’s no reason a C++ program should be using the legacy C headers and functions (such as stdio.h and printf).

  • You should use ARRAY_SIZE in all places where you need the size of that array, otherwise you risk changing it in one place and not the other.

  • Variables should be scoped as tightly as possible. In other words, get rid of the current i declaration and just use for (int i = ....

  • Neither result nor test are changed, nor is buf used for anything, so your entire program boils down to std::cout << "result: 0ntest 5n";.

  • There’s little point to putting argv/c in your main declaration if you don’t use them, just use int main().

  • It’s a good idea to move away from raw pointers, and start using smart pointers – these can automagically deallocate themselves when they go out of scope, leading to easier memory management.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement