By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
457,976 Members | 1,139 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 457,976 IT Pros & Developers. It's quick & easy.

Simple malloc problem with Visual C++ 2005 {Heap}

P: n/a
Hello, I am refreshing my memory on C as I've been in a C++
programming environment for a few months.

Why does the following code produce a heap protection error in Visual
C++ 2005?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char *argv[]){

char
*newString = (char *)malloc(sizeof(char));
strcpy(newString, "2005");
printf("%s\n", newString);
free(newString);

return 0;
}

Nov 15 '05 #1
Share this Question
Share on Google+
2 Replies


P: n/a
AMT2K5 wrote:
Hello, I am refreshing my memory on C as I've been in a C++
programming environment for a few months.

Why does the following code produce a heap protection error in Visual
C++ 2005?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char *argv[]){

char
*newString = (char *)malloc(sizeof(char));
First, lose the cast; this only obscures possible errors. C++ wants
this, C doesn't, and it's generally agreed it shouldn't be done.

Second, you've allocated memory for exactly one character...
strcpy(newString, "2005");


....and then copy 4 characters plus a terminating NUL to this area.

From C++ you're probably used to the idea that you can use 'string' and
get dynamic (re)allocation for free. In C you'll have to do it all
yourself, I'm afraid.

S.
Nov 15 '05 #2

P: n/a
AMT2K5 wrote:
Hello, I am refreshing my memory on C as I've been in a C++
programming environment for a few months.

Why does the following code produce a heap protection error in Visual
C++ 2005?


Your compiler is not relevant. Your code is broken:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void)
{
#if 0
char
*newString = (char *)malloc(sizeof(char));
/* There should be no cast above; since sizeof(char) == 1 by definition,
that makes a lot of the above line just typing practice, better spent
checking the return value from malloc. */
strcpy(newString, "2005");
printf("%s\n", newString);
#endif
printf("sizeof(char) = %lu (ALWAYS),\n"
"sizeof \"2005\" = %lu\n",
(long unsigned) sizeof(char), (long unsigned) sizeof "2005");
#if 0
free(newString);
#endif
return 0;
}

sizeof(char) = 1 (ALWAYS),
sizeof "2005" = 5
Nov 15 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.