Home > Net >  Could someone explain what this simple c code would do?
Could someone explain what this simple c code would do?

Time:10-30

typedef struct{
int x;
int y;
} Coordinate_T;

Coordinate_T *p;
p = (Coordinate_T *)malloc(sizeof(Coordinate_T));
    
p->x = 100;
p->y = 200;
    
free(p);
    
exit(0);

I'm trying to get the hang of pointers but it is really confusing when they are used like this. I got this code from a textbook and I'm supposed to find what's wrong with this code

CodePudding user response:

Woo, it's been a long time since I dealt with C pointers, but let me see if I can help.

Coordinate_T *p;

declares a pointer to a Coordinate_T struct. We don't have any memory available yet, we just have a pointer to... nothing.

p = (Coordinate_T *)malloc(sizeof(Coordinate_T))

actually allocates the memory for us. Now p points to something useful where we can store values. "malloc" is shorthand for "memory allocation." It requires a size - how much memory do you need? "sizeof(Coordinate_T)" is an easy way to say "the size of this struct that I want to point to. Finally, the type cast "(Coordinate_T *)" tells the compiler "treat this like a Coordinate_T pointer".

p->x = 100;
p->y = 200;

Sets the x value of our newly-allocated struct to 100, and the y value to 200. The arrow notation (->) says "p is a pointer; inside the memory it points to, set..."

free(p)

frees the memory you just allocated with malloc(). This means we're done with it, the operating system can use that memory for something else. If you don't free memory when you're done with it, that's a "memory leak" - it's still marked as being in-use, and the operating system can't re-use it. In a long-running program, the leaked memory can build up and build up, and eventually the operating system kills the running program when no more memory is available.

exit(0);

just kills the program, and returns the value zero, which is the traditional value that means "Everything is fine." If a program returns any other value, that means some error occurred.

tl;dr: This program doesn't do much. It sets a couple values, then throws away the memory it used, and exits. It would be more interesting to include a printf() statement to echo those values back to you, but I'll leave that to you. ;-)

  • Related