ProgrammingThis forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.
Notices
Welcome to LinuxQuestions.org, a friendly and active Linux Community.
You are currently viewing LQ as a guest. By joining our community you will have the ability to post topics, receive our newsletter, use the advanced search, subscribe to threads and access many other special features. Registration is quick, simple and absolutely free. Join our community today!
Note that registered members see fewer ads, and ContentLink is completely disabled once you log in.
If you have any problems with the registration process or your account login, please contact us. If you need to reset your password, click here.
Having a problem logging in? Please visit this page to clear all LQ-related cookies.
Get a virtual cloud desktop with the Linux distro that you want in less than five minutes with Shells! With over 10 pre-installed distros to choose from, the worry-free installation life is here! Whether you are a digital nomad or just looking for flexibility, Shells can put your Linux machine on the device that you want to use.
Exclusive for LQ members, get up to 45% off per month. Click here for more info.
Hey eveyone im trying to learn better by messing around with malloc and sizeof but im getting strange resluts.
Code:
#include<stdio.h>
#include<stdlib.h>
int main ()
{
char *test;
test = (char *) malloc (200);
printf("The size of the memory is %d\n",sizeof (test));
free(test);
printf("The size of the memory is %d\n",sizeof (test));
return 0;
}
is there some reason I should be getting only 4 on output ? no mater what
I change the malloc number to?
OUTPUT
------------------
The size of the memory is 4
The size of the memory is 4
Yes. When you do sizeof(test) the result is 4 because a pointer to char is 4 bytes on your machine. Sizeof tells you the size of a particular data type (such as int or pointer to char). Unfortunately, there's no portable way to tell the size of a chunk of alloced memory other than to keep track of it when you alloc it.
You have to understand that sizeof() is not a function call. It purely deals with types and that is something the compiler can determine at compile time. It looks like a function, but it really is a macro. So it looks at sizeof(temp) and converts that to sizeof(char *) and knows that that is 4 bytes. For sizeof(&temp), it sees sizeof(char), which is 1 byte. All of this computation happens at compile time, not runtime.
I tried creating a program that would try and guess what the size of a malloc return was but no go i would have to alredy know what it was before i could figure it out.
LinuxQuestions.org is looking for people interested in writing
Editorials, Articles, Reviews, and more. If you'd like to contribute
content, let us know.