Understanding Mallocs help needed

Started by
1 comment, last by SiCrane 16 years, 1 month ago
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
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.
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.

This topic is closed to new replies.

Advertisement