• ### Popular Now

• 15
• 15
• 11
• 9
• 10

#### Archived

This topic is now archived and is closed to further replies.

# Having problems with malloc

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

## Recommended Posts

I'm using the book 'Teach Yourself C in 24 Hours' and in the chapter about allocating memory, I keep getting the error "cannot convert 'void *' to 'char *' in function main()". Here's the code from the book:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void str_copy(char *str1, char *str2);

main()
{
char str[] = "Allocating memory.";
char *p_str; // pointer to string
int result;

p_str = malloc(strlen(str) + 1); // right here is where I get the error //

if(p_str != NULL)
{
str_copy(str, p_str);
printf("The string pointed to by p_str is: \n%s\n", p_str);
result = 0;
}
else
{
printf("malloc() function failed.\n");
result = 1;
}
return result;
}

void str_copy(char *str1, char *str2)
{
int i;

for(i=0; str1; i++) // there's supposed to be braces around an i after the str1, but for some reason, they aren't showing up in this post //
str2[i] = str1[i];
str2[i] = '\0';
}

It's really bugging me because I'm entering everything just as it is in the book, so I know it's not my fault, or, at least it doesn't seem to be, but I can't figure out what the problem is. Thanks to anyone who can help. [edited by - locus on September 15, 2002 2:36:13 AM]

##### Share on other sites
Are you trying to compile it with a c++ compiler? While the code is valid c, it isn''t valid c++. Try this:

p_str = (char*)malloc(strlen(str) + 1);