Jump to content
  • Advertisement
Sign in to follow this  
gp343

Understanding Mallocs help needed

This topic is 3757 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

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
Advertisement
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
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!