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

A

AMT2K5

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;
}
 
S

Skarmander

AMT2K5 said:
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.
 
M

Martin Ambuhl

AMT2K5 said:
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,020
Latest member
GenesisGai

Latest Threads

Top