Store character string in a block of memory space

Asked By 10 points N/A Posted on -

How can I store a character string in a block of memory space which is created by malloc and then modify the same to store a large string? Can it remain the same while storing the original contents of the buffer even after modifying the original size?

Best Answer by vidish
Best Answer
Best Answer
Answered By 0 points N/A #86686

Store character string in a block of memory space


Hey vipin,
when you create a dynamic memory block using malloc or calloc you will be returned a pointer to the starting memory address.

For e.g.,

 cptr=(char *) malloc(10);  –allocates 10 bytes of space for the pointercptr of type char.

It will return the starting memory address to the cptr and will store each character at the consequent memory addresses.

As character occupies only 1 byte, you can access the next character with the one increment in the starting address and so on.

Like you can store the address of cptr into another pointer and use that pointer increment/decrement to access the other letters in the string.


String                                   g                 o                     o                    g                   l                e

Mem. Address    Cptr —–>1001          1002               1003             1004           1005           1006

So to access 'e' you need to do


once you get access to the character you can modify it simply.
If the new string is larger than your current then you should use realloc.

ptr=realloc(ptr,new size);
If your requested number of bytes are available at the end of the current last bytes, then it most likely remain the same.

If the new larger size is not available at the end of the last byte,then it will reallocate the whole string.


you request to add Google plus in above example and there are only 2 bytes available at the end. i.e.address 1007 ,1008

then whole string will be reallocated.

Answered By 0 points N/A #86688

Store character string in a block of memory space


Malloc usually allocates a contiguous  block of memory, and if does not do that it may end up failing to be operational in case there is no large enough contiguous block available, and that will cause the malloc application to return a NULL pointer during its execution.

The internal memory allocation that of the malloc application will be used to keep track of the amount of memory that has been allocated with that pointer value, and then all of it will be freed.

Some of the problems that you will encounter will include buffer overflows, and these may just may take attackers slightly longer time to find a payload.

-Clair Charles

Login/Register to Answer

Related Questions