What will the following program print and what is not correct in that program? void func(int* x) { x = (int*)malloc(sizeof(int)); *x = 17; } void main() { int y = 42; func(&y); printf("%d",y); }
Anonymous
//1. The given code will not execute, compiler will throw error, as main is returning void //2. Second is not a critical issue with such small code, but, not freeing the allocated space by malloc may result in memory leak if func() is used multiple time it will ultimately overflow the stack allocated to func() void main () //main must return an integer, returning void is incorrect It should be: void func (int* x) { x = (int*) malloc (sizeof (int)); *x = 17; free(x); //memory allocated using malloc is not freed up, so free it up (it will prevent stack overflow, if func() is used many times, every time new memory space will be allocated without freeing up previous one for same purpose) } int main() //main should return an integer, not void, compiler will throw error if returned void { int y = 42; func(&y); printf("%d",y); return 0; //optional, but good to have, if done for embedded firmware, main may continue to overwrite other memory locations, and whole memory map will be corrupted }
Check out your Company Bowl for anonymous work chats.