c - Segmentation fault with char pointer -


i tried run piece of code on windows, , same 1 on linux. while ran fine on windows, gave me segmentation fault in linux. know in code allocated memory getting wasted, can please clarify why linux giving fault while windows not.

char *ptr=(char*)malloc(sizeof(2*10)); ptr="harsh"; printf("%s\n",ptr); 

this code doesn't segfault itself. there bug somewhere else overwriting memory used string "harsh" (so printf crash) or overwriting data structures maintain heap (so malloc crash)

these kinds of problems common beginning programmers, , cause different problems in different environments. since 2 out of 3 lines in program seem have memory-related bugs, seems likely.

one of important things c++ programmer has learn afraid of these kinds of bugs. that's why, in modern c++, use raii , collection classes make sure these kinds of problems don't happen.


Comments

Popular posts from this blog

javascript - Slick Slider width recalculation -

jsf - PrimeFaces Datatable - What is f:facet actually doing? -

angular2 services - Angular 2 RC 4 Http post not firing -