What's wrong with "char *p = malloc(10);" ?

Answers were Sorted based on User's Feedback



What's wrong with "char *p = malloc(10);" ?..

Answer / guest

malloc returns a void pointer. It needs to be cast to char*
before allocating it to char* variable.
char *p = (char *)malloc(10); should do fine.

Is This Answer Correct ?    26 Yes 2 No

What's wrong with "char *p = malloc(10);" ?..

Answer / poornima

Nothing wrong.Its fine..
if u hve further doubt run the below code.

#include<stdio.h>
int main()
{
char *p=malloc(10);
if(p==NULL)
{
printf("malloc failed");
exit(0);
}
else
{
printf("malloc success\n");
p="hai";
printf("%s",p);
}
return 0;
}

o/p:
malloc success
hai

Is This Answer Correct ?    6 Yes 10 No

What's wrong with "char *p = malloc(10);" ?..

Answer / guest

Function calls are not allowed in initializers for global or
static variables.

Is This Answer Correct ?    3 Yes 12 No

What's wrong with "char *p = malloc(10);" ?..

Answer / splurgeop

malloc return an adress to the free memory..so we shud
store the adress i.e.
the above should be

char p=malloc(10);

Is This Answer Correct ?    1 Yes 16 No

Post New Answer

More C Interview Questions

What is 'bus error'?

0 Answers  


dennis ritchie invented C language in AT&T bell laboratory what is the extension of AT&T?

4 Answers  


The % symbol has a special use in a printf statement. Explain how would you place this character as part of the output on the screen?

0 Answers  


Is an array parameter is always "by reference" ?

1 Answers  


print 1-50 with two loop & two print Statement

2 Answers  






Is null always defined as 0(zero)?

0 Answers  


The process of repeatedly running a set of computer instructions until some condition is specifed a) condition b) sequential condition c) global d) iteration

0 Answers  


What is FIFO?

0 Answers  


write a program in reverse the string without using pointer,array,global variable declaration,lib fun only using a function?

5 Answers   HCL,


What is line in c preprocessor?

0 Answers  


what are the advanced features of functions a) function declaration and prototypes b) calling functions by value or by reference c) recursion d) all the above

0 Answers  


Write a simple program to find the size of different basic data types in C.

3 Answers  


Categories