This question already has answers here:
Determine size of dynamically allocated memory in C
(15 answers)
How to get the size of dynamically (using malloc or calloc )allocated memory? [duplicate]
(2 answers)
Closed 9 years ago.
Is there a way to know from a pointer the size with which malloc() was called?
For example, if I have:
typedef struct entry entry_t;
struct entry
{
int val;
};
entry_t *entryt_p = (entry_t *)malloc(10 * sizeof(entry_t));
Is there a way I can extract from entryt_p with which size malloc() was called?
There isn't a portable way specified by the language. Some versions of malloc may offer an extension to do it. In general, it's up to your program to keep track.
There is no way for the user to access this information. Malloc returns a pointer to the address of the memory that was allocated.
It is up to the program to keep track of how much was allocated.
If you really don't want to keep track of the size consider using a sentinel value in the last position.
Related
This question already has answers here:
Can we have a struct element of type Variable length array? [duplicate]
(5 answers)
Closed 2 years ago.
I would like to define array size inside a structure by using a parameter of this structure. Does C permit to do something like this ?
struct queue {
int head;
int top;
int size;
struct action action[size];
};
No you can't. Since action is not a dynamic variable, the compiler needs to know at compile time how much space it needs for action. size was not even initialized. Anyway, you could see this just by trying to compile.
The size is not known at the time of defining the struct. Therefore it is impossible for the compiler to understand how large the result will be. Typically, you would first allocate memory for the struct, and have a struct action *action; member. After initializing the struct, you use instance->action = calloc(instance->size, sizeof *instance->action) to allocate memory for the array.
This question already has answers here:
Undefined, unspecified and implementation-defined behavior
(9 answers)
Is it undefined behaviour to access an array beyond its end, if that area is allocated? [duplicate]
(3 answers)
Array index out of bound behavior
(10 answers)
Getting no segmentation fault when exceeding the size that was allocated for a char * [duplicate]
(1 answer)
Closed 5 years ago.
The title may not be accurate. Please excuse me for being a completely new programmer in c. But it is a genuine question which I believe will benefit others who were as confused by memory and pointers as I was when learning my first low-level programming language, that is C.
Here is what I know in regard to this:
Pointers are variables that store memory addresses.
You can allocate a place in memory using the malloc function from the stdlib.h header file, which returns a pointer to the memory allocated.
The malloc function takes the size of what you want to store in bytes as a parameter
Which leads me to ask: What if you store something of a bigger size in the place in memory allocated by the malloc function, where you passed a smaller size as the parameter for the malloc function?
Naturally, the first thing I did was obviously try it. I take input using scanf, which then stores the input in the allocated memory. Here is the code:
#include <stdio.h>
#include <stdlib.h>
int main(){
char *string_pointer;
string_pointer = malloc(sizeof(char)*24);
if (string_pointer == NULL){
puts("Memory allocation failed:(");
return 1;
}else{}
scanf("%s",string_pointer);
printf("%s",string_pointer);
return 0;
}
You can see that I allocated a place in memory, passing in sizeof(char)*24 as the parameter. Then I stored the pointer of this memory in the string_pointer variable.
Now if I feed scanf with a string that is more than 24 characters (bigger size than the allocated memory), it still works, When I print out the contents of the memory, I get the whole string as it is, even though that means that it stored a string of a bigger size than what it can hold. This shows that I have an obvious misconception of how memory allocation works. It might be because that malloc doesn't allocate a memory that can only hold the size that I passed to malloc, and the whole size parameter thing is for a totally different purpose.
I am completely confused? How come I just stored a string in a memory allocated that can hold less than the size of the string?
This question already has answers here:
How do free and malloc work in C?
(8 answers)
Closed 6 years ago.
/*Pointer Array (Dynamic) EXAMPLE*/
int size = 0;
printf("Enter the size of the array you want:\n");
scanf("%d",&size);
int * Dptr = malloc(sizeof(*Dptr)*size);
if(!Dptr)
return -1;
for(int i=0;i<size;i++)
Dptr[i]= -7;
printf("Congratulations, you successfully allocated and wrote to a dynamic array.\n");
free(Dptr); //how does it "know" what to deallocate? Is everything getting proprely reclaimed?
Above the a little doodle in C I wrote, I had a question about memory allocation concerning dynamic arrays. At the end I call the free function to deallocate the memory of the array I allocated, but my question is, how does it "know" how much memory to deallocate? Or, is it just deallocating the first int and leaving everything else dangling? If so, what is the proper way to reclaim this memory?
The free call releases the entire buffer; a single malloc call should correspond to a single free call.
As to how it knows... well, that's going to depend on the implementation. But if you're just looking for peace of mind, consider this:
If the system didn't know how big the buffer was, how would it know where it could start the next dynamic allocation (if you should call malloc again without having freed the first buffer)?
This is all the responsibility of the memory management libraries. It will work in any properly implemented system.
This question already has answers here:
How do I correctly set up, access, and free a multidimensional array in C?
(5 answers)
Closed 6 years ago.
I already have an idea on how to malloc a matrix if it were an int**. But using a typedef, I think have an idea but I'm not so sure.
typedef int LabeledAdjMatrix[SIZE][SIZE];
Do I do it like this?
APSP = (APSPMatrix*)malloc(sizeof(APSPMatrix));
But when I access it I'm gonna have to use *APSP[0][0] and I have no idea how to use this in memset/memcpy.
Is there a proper way of doing this? Both in dynamically allocating and in accessing.
My advice would be to not use array typedefs, they make the code harder to read as it is less apparent when array-pointer decay is or isn't happening.
If you want to allocate a contiguous array you can write:
int (*APSP)[SIZE] = malloc( sizeof(int[SIZE][SIZE]) );
and then access it as APSP[0][0].
Your post talks about "malloc as if it were int **", by which I assume you mean you want separate allocations for each rows... but then you would write int **APSP and write a loop to allocate each row, it is really nothing to do with [SIZE][SIZE].
This question already has answers here:
When is malloc necessary in C?
(8 answers)
Closed 8 years ago.
It is often said to use malloc when size is known at run time we could also write
int x;
scanf("%d",&x);
char arr[x];
so why use malloc when we can declare array on the fly.
Writing char arr[x]; will allocate the memory on the stack.
The size of the stack is typically limited to around 1MB. You'll get runtime errors if you exceed this pre-defined amount. Some compilers will allow you to change the stack size, but you'll still hit a limit eventually of many orders of magnitude than you can get with malloc.
VLA [Variable length array] is a concept present in C99 onwards.
malloc() originates much before that.
Also, malloc() and family allocates memory from heap. It does not use the comparatively limited stack space.
OTOH, gcc allocates space for VLAs in the stack itself.