xpress_embedo
Advanced Member level 4
Hello!!! I am using Ubuntu 14.04 and Code::Block13.12, to write a program in C Language.
In this Program i have to return a Structure Pointer from a function.
I want to know whether the following written program is logically correct or not, as it is working properly..
Here is my Code:-
In Function DisplayCoordinate, is this line is correct.
Coordinates = (LAT_LONG *)malloc(sizeof(LAT_LONG));
I had allocated the memory but not freed it, where to write the free(Coordinates), or the compiler do it automatically.
If Compiler doesn't do it, then how can i do it what would happen if i call this function multiple times.
Is it true that each time a new memory is allocated.???
In this Program i have to return a Structure Pointer from a function.
I want to know whether the following written program is logically correct or not, as it is working properly..
Here is my Code:-
Code C - [expand] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 #include <stdio.h> #include <stdlib.h> typedef struct { unsigned char Latitude[9]; unsigned char Longitude[10]; }LAT_LONG; LAT_LONG *DisplayCoordinate(void); int main() { LAT_LONG *Coordinates; unsigned char i=0; Coordinates = DisplayCoordinate(); printf("\nLatitude = "); for(i=0;i<9;i++) printf("%c",Coordinates->Latitude[i]); printf("\nLongitude = "); for(i=0;i<10;i++) printf("%c",Coordinates->Longitude[i]); return 0; } LAT_LONG *DisplayCoordinate(void) { LAT_LONG *Coordinates; Coordinates = (LAT_LONG *)malloc(sizeof(LAT_LONG)); Coordinates->Latitude[0] = '6'; Coordinates->Latitude[1] = '1'; Coordinates->Latitude[2] = '2'; Coordinates->Latitude[3] = '6'; Coordinates->Latitude[4] = '.'; Coordinates->Latitude[5] = '6'; Coordinates->Latitude[6] = '6'; Coordinates->Latitude[7] = '6'; Coordinates->Latitude[8] = '6'; Coordinates->Longitude[0] = '0'; Coordinates->Longitude[1] = '1'; Coordinates->Longitude[2] = '2'; Coordinates->Longitude[3] = '3'; Coordinates->Longitude[4] = '4'; Coordinates->Longitude[5] = '.'; Coordinates->Longitude[6] = '1'; Coordinates->Longitude[7] = '0'; Coordinates->Longitude[8] = '0'; Coordinates->Longitude[9] = '0'; return (Coordinates); }
In Function DisplayCoordinate, is this line is correct.
Coordinates = (LAT_LONG *)malloc(sizeof(LAT_LONG));
I had allocated the memory but not freed it, where to write the free(Coordinates), or the compiler do it automatically.
If Compiler doesn't do it, then how can i do it what would happen if i call this function multiple times.
Is it true that each time a new memory is allocated.???