Sign in to follow this  
gp343

Understanding Mallocs help needed

Recommended Posts

Hi there, I'm currently learning C and I'm working with malloc and free. However, I've gotten stock on the below program. I've tried everything and cannot move forward. I understand that every malloc should be followed by a free statement. However, the below program prints allot of funny characters on screen. Can somebody please help me out here? #include <windows.h> #include <stdio.h> #include <conio.h> #include <tchar.h> static TCHAR szAppName[] = TEXT ("James OpenGL Rosette Animation (c) 2008 by James Kerry, Jr.") ; static TCHAR titleBar[25] = {0}; static TCHAR* result2 = NULL; static int FPS = 277.0f; main() { printf("Starting Malloc Test....\n"); sprintf(titleBar, "%d FPS", FPS); result2 = (TCHAR *)malloc(150 * sizeof(TCHAR)); strcat(result2, szAppName); strcat(result2, " "); strcat(result2, titleBar); printf("%s", result2); free(result2); getch(); } Thanks, J

Share this post


Link to post
Share on other sites
I've just solved it. I wasn't initializing my dynamic array correctly. so I put in a memset (result2,0,150); right after my malloc.


Thanks.

Share this post


Link to post
Share on other sites
You don't actually need an explicit initialization for your buffer. A couple of the more obvious alternatives: 1) You can use calloc() instead of malloc() to obtain the memory. calloc() works like malloc() except that calloc() automatically zeros the memory. 2) You can replace your first strcat() with a strcpy(), which will copy the string without searching for a null to concatenate the string.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this