Thread: Basic Doubt on Pointers

  1. #1
    Registered User
    Join Date
    Nov 2018
    Posts
    32

    Question Basic Doubt on Pointers

    I would like to know if there is any command or way of knowing the memory allocated from a pointer in the following conditions:

    MyPointer is a char pointer (char *MyPointer)
    It has 300 bytes allocated to be used! Type using malloc
    It stores the text: cprogramming (12 Bytes)

    How do I know how many allocated bytes (memory allocated) have my pointer?
    That is, what command can I use to result in 300?

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,126
    There is no portable way to know that just from the pointer itself.

    If you need to know, you need to keep track of it yourself by using another variable.

    A good way would be to use a struct.
    Code:
    struct foo {
        char *ptr;
        size_t size;
    }
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered User rstanley's Avatar
    Join Date
    Jun 2014
    Location
    New York, NY
    Posts
    950
    Quote Originally Posted by marcelo.br View Post
    I would like to know if there is any command or way of knowing the memory allocated from a pointer in the following conditions:

    MyPointer is a char pointer (char *MyPointer)
    It has 300 bytes allocated to be used! Type using malloc
    It stores the text: cprogramming (12 Bytes)

    How do I know how many allocated bytes (memory allocated) have my pointer?
    That is, what command can I use to result in 300?
    If you ask malloc() for 300 bytes, and malloc() returns a valid pointer not NULL, then you can be assured that you have 300 bytes but no more!

    There is no function to later return the size of the allocation. You have to keep track of that number in your code. Use a #define. Or use a struct as Salem suggests.

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    #define DIM 300
    
    int main(void)
    {
       char *MyPointer = NULL; // Always initialize all local variables
    
       MyPointer = malloc(DIM);  // Allocate 300 bytes
    
       if(MyPointer != NULL)
       {
          printf("The allocation was successful!\n");
       }
    
       // You are now assured that you have 300 bytes, and only 300 bytes
       // to use for whatever you need it for.
    
       // ... Your other code here
    
       free(MyPointer);  // Free the memory
       MyPointer = NULL; // Prevent attempting to access the freed memory later in the program
    
       return 0;
    }

  4. #4
    Registered User
    Join Date
    Feb 2019
    Posts
    963
    Marcelo (my countryman! I'm from br too! Vitória/ES)...

    The fact is pointers are types which stores a memory address, but nothing else. There is no information about the size of the block pointed by a pointer. So your code must keep track of this information.

    []s
    Fred

  5. #5
    Registered User awsdert's Avatar
    Join Date
    Jan 2015
    Posts
    1,579
    There is a way to trick the system into checking it for you, does however slow the program down, the original video I watched used pipes to check it but I went and wrote something using a different system api, I haven't checked it works but the principle is the same:

    Code:
    #ifdef _WIN32
    dint isPointerValid( void *ptr, ucap bytes )
    {
    	if ( ptr )
    		/* TODO: See if WriteProcessMemory can be used to check pointers */
    		return ENOTSUP;
    	return EFAULT;
    }
    #else
    #include <sys/uio.h>
    dint isPointerValid( void *ptr, ucap bytes )
    {
    	if ( ptr )
    	{
    		struct iovec io = { ptr, bytes };
    		ssize_t did = process_vm_writev( getpid(), &io, 1, &io, 1, 0 );
    		if ( did < 0 )
    			return errno;
    		return 0;
    	}
    	return EFAULT;
    }
    #endif

  6. #6
    Registered User rstanley's Avatar
    Join Date
    Jun 2014
    Location
    New York, NY
    Posts
    950
    Quote Originally Posted by awsdert View Post
    There is a way to trick the system into checking it for you, does however slow the program down, the original video I watched used pipes to check it but I went and wrote something using a different system api, I haven't checked it works but the principle is the same:
    Perhaps you should check to see if it compiles and executes corectly, BEFORE posting an alleged solution to a user:
    Code:
    foo.c: In function ‘main’:
    foo.c:28:4: error: unknown type name ‘dint’; did you mean ‘int’?
       28 |    dint isPointerValid( void *ptr, ucap bytes )
          |    ^~~~
          |    int
    foo.c:28:36: error: unknown type name ‘ucap’
       28 |    dint isPointerValid( void *ptr, ucap bytes )
          |                                    ^~~~

  7. #7
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,126
    I'm baffled as to how it's even remotely close to answering the original question.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  8. #8
    Registered User awsdert's Avatar
    Join Date
    Jan 2015
    Posts
    1,579
    Quote Originally Posted by rstanley View Post
    Perhaps you should check to see if it compiles and executes corectly, BEFORE posting an alleged solution to a user:
    Code:
    foo.c: In function ‘main’:
    foo.c:28:4: error: unknown type name ‘dint’; did you mean ‘int’?
       28 |    dint isPointerValid( void *ptr, ucap bytes )
          |    ^~~~
          |    int
    foo.c:28:36: error: unknown type name ‘ucap’
       28 |    dint isPointerValid( void *ptr, ucap bytes )
          |                                    ^~~~
    It was copy pasted from my own code, if people copying it can't work out how to replace a type that's clearly of integer origin then they shouldn't be programming yet

  9. #9
    Registered User awsdert's Avatar
    Join Date
    Jan 2015
    Posts
    1,579
    Quote Originally Posted by Salem View Post
    I'm baffled as to how it's even remotely close to answering the original question.
    He wanted to check if a pointer actually has X bytes so I mentioned a solution I know of, I know it's imperfect but it does avoid segfaults caused by just trying to access the memory, doesn't check for situations like this though:
    Code:
    int main() { char a = 0, b = 0, c = 0; stringcopy( &a, "12", 2 ); }
    int stringcopy( char *a, char *b, size_t n )
    {
       int err = isPointerValid( &a, n );
       if ( err ) return err;
       memcpy( a, b, n );
       return 0;
    }
    Corruption will still occur in such a situation, checking if n bytes should be accessible for the pointer is still impossible without correct information being fed to the function

  10. #10
    Registered User
    Join Date
    Apr 2021
    Posts
    92
    There is no mechanism mandated by the C standard to work.

    However, most libraries implicitly have this information, since they want to be able to re-use the memory if you free() the allocation. And so, they make the information available to you using their own individual mechanism. You'll have to make different calls depending on what system/library you are using.

    Here's a thread that discusses this, and provides some answers:

    Determine size of dynamically allocated memory in C - Codegrepr

  11. #11
    Registered User rstanley's Avatar
    Join Date
    Jun 2014
    Location
    New York, NY
    Posts
    950
    Quote Originally Posted by awsdert View Post
    It was copy pasted from my own code, if people copying it can't work out how to replace a type that's clearly of integer origin then they shouldn't be programming yet
    You regularly post buggy code that you have not compiled and tested. Plus, what is 'ucap'?

    The majority of the users here are beginners, and it is NOT fair to force a beginner to debug your code before seeing if it answers their questions.

    Where is the documentation for both isPointerValid(), and stringcopy()? Please show me the man pages for both!

    Bottom line, this does not answer the users question. There is no standard way to inquire to the size of an allocation.

  12. #12
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,126
    > He wanted to check if a pointer actually has X bytes so I mentioned a solution I know of
    A task which your attempt fails miserably at.

    No, that isn't the question they asked.
    Quote Originally Posted by marcelo.br View Post
    How do I know how many allocated bytes (memory allocated) have my pointer?
    That is, what command can I use to result in 300?
    They wanted to find X.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  13. #13
    Registered User awsdert's Avatar
    Join Date
    Jan 2015
    Posts
    1,579
    Quote Originally Posted by rstanley View Post
    You regularly post buggy code that you have not compiled and tested.
    IALWAYS compile and test it, it just that what worked for me didn't happen to work for another, that's just a normal thing in programming, if you can't get your head out of your ass and accept that then you should keep quite in these forums.

    Quote Originally Posted by rstanley View Post
    Plus, what is 'ucap'?
    That depends on the OS, on _WIN32 it's DWORD, anywhere else it's size_t, I'm trying to design my library to not use microsoft's buggy versions of the standard C library, musl is nice but since I'm supporting _WIN32 as best I can I might as well just skip standard c libs there and go straight for the OS calls, for now the code's not yet there but it will be eventually, I've even decoupled thread safety from the thread APIs, the only thing I needed to that end was a callback that just needs to be re-directed from the empty function it defaults to to one that makes the thread yield it's execution slice. No mutexes or semaphores need, just some pointers that should be NULL by default.

    Quote Originally Posted by rstanley View Post
    The majority of the users here are beginners, and it is NOT fair to force a beginner to debug your code before seeing if it answers their questions.
    In those case that's fair, but in this case the OP does not sound like a beginner, and I'm sure they're familiar with malloc & realloc, I really doubt they need telling how to convert the function to their own uses

    Quote Originally Posted by rstanley View Post
    Where is the documentation for both isPointerValid(), and stringcopy()? Please show me the man pages for both!
    If you can't tell what to expect from them & what to pass them despite seeing the code then you might need to relearn C, they are both cases where documentation is overkill, furthermore as I mentioned I haven't done a proper test for isPointerValid so documenting it would be stupid even if it did happen to work, experimental code & small example code should never be documented, it just adding useless fluff for the sake of a poll up one's own ass.

    Quote Originally Posted by rstanley View Post
    Bottom line, this does not answer the users question. There is no standard way to inquire to the size of an allocation.
    It does partially answer the users question to the extent of "you can confirm the amount of bytes that can be accessed without segfaulting", knowing if they can be accessed is an implicit requirement of any solution.

  14. #14
    Registered User awsdert's Avatar
    Join Date
    Jan 2015
    Posts
    1,579
    Quote Originally Posted by Salem View Post
    > He wanted to check if a pointer actually has X bytes so I mentioned a solution I know of
    A task which your attempt fails miserably at.

    No, that isn't the question they asked.


    They wanted to find X.
    I never said it was a complete solution, as my previous post mentions it is a partial solution and far from ideal nor recommended, I was simply showing him the only option I know of that can be used with information given to the code being executed, I still prefer to use structures that are unlikely to be maliciously damaged which means in most cases it can be more reliable than trying to fish the size stored by whatever allocators are in use, with how many versions of malloc & realloc alone there likely are I would not even consider trying to do it the way the OP was trying.

  15. #15
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,126
    > I never said it was a complete solution,
    No, it was never a solution to the problem at all, and never could be made into a solution to the problem.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Basic C++ program doubt.
    By nitinmadan2015 in forum C++ Programming
    Replies: 3
    Last Post: 01-19-2016, 07:22 AM
  2. Basic doubt
    By pshirishreddy in forum C++ Programming
    Replies: 2
    Last Post: 09-15-2009, 11:00 AM
  3. basic doubt
    By vikranth in forum C Programming
    Replies: 7
    Last Post: 10-30-2007, 11:21 AM
  4. basic doubt
    By sincere_cute in forum C Programming
    Replies: 2
    Last Post: 06-20-2007, 03:33 AM
  5. [B]a basic doubt !![/B]
    By samirself in forum C Programming
    Replies: 6
    Last Post: 04-30-2005, 01:39 PM

Tags for this Thread