A list of puns related to "C Dynamic Memory Allocation"
#include<stdio.h>
#include<stdlib.h>
int i,j;
int **readMatrix(int rows,int cols){
int **a;
a=(int**)malloc(rows*sizeof(int*));
for(i=0;i<rows;i++){
a[i]=(int*)malloc(cols*sizeof(int));
Β Β }
for(i=0;i<rows;i++){
for(j=0;j<cols;j++){
scanf("%d",&a[i][j]);
Β Β Β Β }
Β Β }
return a;
Β Β }
void displayMatrix(int **a,int rows,int cols){
for(i=0;i<rows;i++){
for(j=0;j<cols;j++){
printf("%d ",a[i][j]);
Β Β Β Β }
printf("\n");
Β Β }
}
int main(){
int n,**a;
scanf("%d",&n);
a=readMatrix(n,n);
displayMatrix(a,n,n);
for(i=0;i<n;i++){
free(a[i]);
Β Β }
free(a);
return 0;
}
Hi guys, I'm learning C++ and I don't quite get the difference or the usefulness of dynamic array allocation. I wrote a short program that makes an array of both size and prints it out. Can you guys explain to me what the difference is and why I should use dynamic memory allocation (if true)?
#include <iostream>
void arrayMake();
void dynamicArrayMake();
int main()
{
arrayMake();
dynamicArrayMake();
return 0;
}
//Input array size, make array, print [array]
void arrayMake()
{
int arraySize = 1;
std::cout << "\nEnter array size: ";
std::cin >> arraySize;
int array[arraySize] = {0};
for (int i: array)
std::cout << *(array+i);
}
//Input array size, make array, print [dynamic memory array]
void dynamicArrayMake()
{
int arraySize = 1;
std::cout << "\nEnter array size: ";
std::cin >> arraySize;
int* dynamicArray = new int[arraySize];
for (int i = 0; i < arraySize; i++)
std::cout << *(dynamicArray+i);
}
ptr = (int*)malloc(5*sizeof(int));
if a allocate 5*size(int) to ptr, do I give to ptr 20 addresses to work on? and how the pointer keeps tracking the addresses given, coz the addresses can't be like *****1,*****2,*****3,... so they gonna be in different places on the memory or am wrong?
Looking for a systems programmer familiar in C that knows how to design a dynamic storage allocator (malloc, free, realloc). Similar exercise to the malloc lab. Tutoring at an hourly rate of $20 is also welcome, message me if interested!
How it works (see section about Fast pimpl): https://blockspacer.github.io/flex_docs/tutorial/
Ready-to-use code generator: https://github.com/blockspacer/flex_pimpl_plugin
Like many programmers before me, I have gotten to the dreaded rite of learning about pointers in C. I am incredibly confused and not very good at using them. Does anyone have any good introductory resources to get my feet wet and help me understand these two concepts?
Thanks in Advance!
Out of curiosity:
Has anyone here witnessed a somewhat general purposey language that doesn't allow dynamic allocations or at least stack-only allocations? (Not including Forths and old Fortran but including scripting languages of some sorts, that is.)
Follow-ups:
I made a A* path finder in C. Github: https://github.com/felselva/uastar
A bunch of implementations online use dynamic memory allocation to allocate (and free) nodes, so I wanted something without that.
Here is a small ugly GIF of the test under work: https://i.imgur.com/upkFBiV.gifv
The test generates a random map based on percentage of passable paths, a seed number and size. The position of the start and end is also set on the command line. The first argument (1) tells to show the progress, which is the case shown in the GIF.
I am trying to dynamically reallocate memory depending on the size of a user's string input, but my code is outputting a few more characters than expected. However, when I tried making some minor changes to a few lines (the lines commented out) it works perfectly fine:
Works fine (user inputs "test", allocates space for 4 + 1 ('\0') bytes, prints "test":
int main() {
char* dyStr = dyn_strIn();
puts(dyStr);
// OUTPUT:
// test // USER INPUT
// test // PRINTED
return 0;
};
char *dyn_strIn()
{
char *line = NULL, *tmp = NULL;
size_t size = 0, index = 0;
int ch = EOF; // EOF == -1
while (ch) {
ch = getc(stdin);
/* Check if we need to stop. */
if (ch == EOF || ch == '\n')
ch = 0;
/* Check if we need to expand. */
if (size <= index) {
size += BLOCK_SIZE; // how much more space to allocate
tmp = (char*)realloc(line, size);
if (!tmp) {
// could not reallocate
free(line);
line = NULL;
break;
}
line = tmp;
}
/* Actually store the thing. */
line[index++] = ch;
}
return line;
}
Outputs more chars than expected :
int main() {
char* dyStr = dyn_strIn();
puts(dyStr);
// OUTPUT:
// test // USER INPUT
// test // PRINTED
// Β²Β²Β²Β² // PRINTED
return 0;
};
char* dyn_strIn() {
char* line = NULL, * tmp = NULL;
size_t size = 0, index = 0;
char ch = NULL;
while (ch != '\n') {
ch = getc(stdin);
if (size <= index) {
// check if need to expand
size += BLOCK_SIZE; // how much more space to allocate
tmp = (char*)realloc(line, size); // assign line to temp in case line returns nullptr
if (!tmp) {
// could not reallocate
free(line);
line = NULL;
break;
}
line = tmp;
}
line[index++] = ch;
}
return line;
}
I just learned about dynamic memory allocation using the alloc commands (malloc, calloc, realloc and so on).
If I create a nondynamic field, let's say an int array, I can ask about its size:
int ar[5]={};
If I now ask my program about the size of int and sizeof ar, it will give me 4 and 20, so it knows that ar is long enough for five integers.
But if I create a dynamic field, I cannot get such a reply. If I say
int *dm=(int*)calloc(5, sizeof(int));
then all I get is a pointer of a size of 4 bytes, that points to a single integer of 4 bytes. As far as I know I cannot get the information about the field size from the pointer anymore, I have to save it manually.
Since that is the case, how does C remember how long a dynamically allocated field is? After all it must know, so it does not overwrite anything in it, and so it can actually use free() without leaving anything.
And what happens if I create a dynamically allocated field of let's say 5 ints inside a function, and then return the pointer to it to main? Is my field still save while I'm working on it in main, or is my allocated memory in risk of being overwritten? And will free() still work on the returned pointer, or will it now just free the first integer in it? Or will my program only know the size of the field within the bounds of its declaration?
Hi. I would like to know when we use new to dynamically allocate memory, we use a dereferencing to access the value at the address like this
int* sample = new int(5);
cout << *sample<< endl;
But when we allocate a block of memory and try to access the value in an array, why don't we use a dereference?
int* p = new int[3];
/* assign values */
cout << p[i] << endl;
Here we are not using the deferencing to print out the values.
Hi there, the code I'm writing calls for some large arrays (1 million+ elements) and I've found that to do this you need to use malloc.
I know that you need to free the memory after you've finished with it using free() but is that everything I need to know? I don't feel I know enough about computers to start dealing with memory leaks so just trying to be safe
edit: also is there a way to know the maximum size of memory which can be allocated on the stack?
I am learning C (my first programming language) and I am having a hard time wrapping my head around malloc. Could someone help me better understand what it is for/what it is doing?
Quoting: http://www.cplusplus.com/doc/tutorial/dynamic/
> Until now, in all our programs, we have only had as much memory available as we declared for our variables, having the size of all of them to be determined in the source code, before the execution of the program. But, what if we need a variable amount of memory that can only be determined during runtime? For example, in the case that we need some user input to determine the necessary amount of memory space.
What kind of situations is the text referring to?
I was watching a video about binary search trees, and I noticed their code was using "new" statements, but they never put any "delete" statements.
I was always taught that every "new" statement had to have a corresponding "delete" statement.
Here's the link their github page for the source.
I looked at other BST implementations, and all of those also had "new" statements without matching "delete" statements. Is there a reason why they're not deleting it at the end, or have I been looking at bad code? Or am I just an idiot and not understanding something basic?
Please note that this site uses cookies to personalise content and adverts, to provide social media features, and to analyse web traffic. Click here for more information.