Thao Nguyen
Thao Nguyen

Reputation: 901

error malloc in C

I'm not sure whats wrong with this it says incompatible implicit built in func Well I did include string.h file but it still giving me a error

 int name_read;
 int name_bytes = 100;
 char *name;

 printf("Please enter name:\n");
 name = (char *)malloc(name_bytes + 1);
 name_read = getline(&name, &name_bytes, stdin);

Upvotes: 0

Views: 703

Answers (3)

MByD
MByD

Reputation: 137412

I think you actually need name = malloc(name_bytes + 1); (assuming you want to allocate 101 bytes for name)

Upvotes: 0

prelic
prelic

Reputation: 4518

To fix the error, make sure you've included stdlib.h. Also, you should note that sizeof returns the size of a variable/type, not the value assigned to the variable. So your sizeof(name_bytes) will return the size of an integer in bytes, not 100

Upvotes: 0

John Ledbetter
John Ledbetter

Reputation: 14203

You need to #include <stdlib.h> to get the correct declaration of malloc.

Also sizeof(name_bytes) + 1 looks fishy; that will give you 5 bytes of memory, not 101 as you probably expected.

Finally, there is no need to cast the return value of malloc in C since it returns a void*.

#include <stdlib.h>
/* ... */
int name_bytes = 100;
char* name = malloc(name_bytes + 1);

Upvotes: 8

Related Questions