C displays a -106 instead of 150 when using malloc() | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

C displays a -106 instead of 150 when using malloc()

So I set a malloc to a pointer. At the 3rd allocated spot I set it to an integer and it works. And I set another allocated spot in the malloc to 150, yet when I print it out it displays -106 instead of 150. Why is this happening? On a side note, is there any way at all to make template functions or generics in C? You can't even compare data types to my knowledge. If I want a function that prints out the parameter despite the datatype, is it possible? eg - void func(unknown_type x){ unknown_type var = x; printf("%unknown_type", var); } func("hello"); func(4); >>> hello >>> 4 https://code.sololearn.com/cUoVazL235J9/?ref=app

28th Apr 2021, 6:17 AM
Clueless Coder
Clueless Coder - avatar
3 Answers
+ 2
Generics in C work with a combination of void pointers and macros, but nothing as straightfoward as the C++ template system. For example, the C standard library uses macros to implement type generic math operations. Here you can find a discussion of techniques: https://stackoverflow.com/questions/3039513/type-safe-generic-data-structures-in-plain-old-c The following is a tutorial delving into how to use them to implement generic data structures: https://iafisher.com/blog/2020/06/type-safe-generics-in-c Since C11, there is also the _Generic() macro, which works a little bit like a switch statement, but for types. You can find more information here: https://stackoverflow.com/questions/9804371/syntax-and-sample-usage-of-generic-in-c11 https://en.cppreference.com/w/c/language/generic Sample codes from another user that make use of _Generic: https://code.sololearn.com/c1AP1N5OYRys/?ref=app https://code.sololearn.com/cu21840C023D/?ref=app
28th Apr 2021, 7:15 AM
Shadow
Shadow - avatar
+ 4
I don't know if this is intentional, but you are allocating space for twenty integers, but then assign the pointer to a char pointer. This means the allocated memory is now interpreted as a range of characters, and a char has a size of 1 byte. With one byte, you can represent the signed range [ -128, 127 ]. Since 150 is out of that range, it wraps back around. The bit pattern of 150 is 10010110 which is interpreted as 1*2^7 - ( 0*2^6 + 0*2^5 + 1*2^4 + 0*2^3 + 1*2^2 + 1*2^1 + 0*2^0 ) = -106. If you wanted to operate on integers, you would have to use an int pointer to store the allocated space, since the bytes in memory are interpreted according to the type of the pointer.
28th Apr 2021, 6:55 AM
Shadow
Shadow - avatar
0
Shadow thanks
28th Apr 2021, 7:00 AM
Clueless Coder
Clueless Coder - avatar