I am a newbie in C coding, just wanted to verify if I have used the free() function correctly here. This is a code to scan and print a square matrix using 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;
}

πŸ‘︎ 5
πŸ’¬︎
πŸ‘€︎ u/sexytwink2
πŸ“…︎ Jan 12 2022
🚨︎ report
C++ Regular Array vs Dynamic Memory Allocation?

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 &lt;iostream&gt;
void arrayMake();
void dynamicArrayMake();

int main()
{
    arrayMake();
    dynamicArrayMake();
    return 0;
}
//Input array size, make array, print [array]
void arrayMake()
{
    int arraySize = 1;
    std::cout &lt;&lt; "\nEnter array size: ";
    std::cin &gt;&gt; arraySize;
    int array[arraySize] = {0};

    for (int i: array)
        std::cout &lt;&lt; *(array+i);
}
//Input array size, make array, print [dynamic memory array]
void dynamicArrayMake()
{
    int arraySize = 1;
    std::cout &lt;&lt; "\nEnter array size: ";
    std::cin &gt;&gt; arraySize;
    int* dynamicArray = new int[arraySize];

    for (int i = 0; i &lt; arraySize; i++)
        std::cout &lt;&lt; *(dynamicArray+i);
}
πŸ‘︎ 6
πŸ’¬︎
πŸ‘€︎ u/Anthonyy232
πŸ“…︎ Nov 16 2021
🚨︎ report
Dynamic Memory Allocation in C

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?

πŸ‘︎ 7
πŸ’¬︎
πŸ‘€︎ u/who_not
πŸ“…︎ Oct 09 2021
🚨︎ report
constexpr Dynamic Memory Allocation, C++20 - variable size containers allowed! cppstories.com/2021/const…
πŸ‘︎ 137
πŸ’¬︎
πŸ‘€︎ u/joebaf
πŸ“…︎ Mar 22 2021
🚨︎ report
constexpr Dynamic Memory Allocation, C++20 - variable size containers allowed! cppstories.com/2021/const…
πŸ‘︎ 43
πŸ’¬︎
πŸ‘€︎ u/joebaf
πŸ“…︎ Mar 23 2021
🚨︎ report
[HIRING] Dynamic Memory Allocation in C (flat rate of $200)

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!

πŸ‘︎ 3
πŸ’¬︎
πŸ“…︎ Apr 14 2021
🚨︎ report
C++ pimpl code generator. Fast pimpl without overhead! No dynamic memory allocation! Cache-friendly! Auto-detects storage size! Generates methods based on implementation!

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

πŸ‘︎ 15
πŸ’¬︎
πŸ‘€︎ u/derofim
πŸ“…︎ Jun 01 2020
🚨︎ report
Good resources to learn Pointers and Dynamic Memory Allocation in C?

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!

πŸ‘︎ 4
πŸ’¬︎
πŸ‘€︎ u/ImmoralDarkness
πŸ“…︎ May 05 2020
🚨︎ report
Programming languages without dynamic memory allocation?

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:

  • Do you have interesting ideas for specific features?
  • Do you have an intuition on what the overhead of dynamic memory allocation typically is?
πŸ‘︎ 37
πŸ’¬︎
πŸ‘€︎ u/Quecksilberbarren
πŸ“…︎ Jan 08 2022
🚨︎ report
Dynamic Memory Allocation in C - malloc, free, and buffer overflows | Gary Explains youtube.com/watch?v=wadj1…
πŸ‘︎ 2
πŸ’¬︎
πŸ‘€︎ u/SomeGadgetGuy
πŸ“…︎ Jun 16 2020
🚨︎ report
UASTAR - A* path finder in pure C without dynamic memory allocation

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.

πŸ‘︎ 42
πŸ’¬︎
πŸ‘€︎ u/felselva
πŸ“…︎ Jan 30 2019
🚨︎ report
Dynamic allocation of memory for string input outputs more chars than expected?

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 &lt;= 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 &lt;= 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;
}
πŸ‘︎ 5
πŸ’¬︎
πŸ‘€︎ u/chandyego84
πŸ“…︎ Jan 04 2022
🚨︎ report
Question about dynamic memory allocation in C - how does C remember how large a dynamic field is?

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?

πŸ‘︎ 21
πŸ’¬︎
πŸ‘€︎ u/Roflkopt3r
πŸ“…︎ Apr 18 2015
🚨︎ report
A question about dynamic memory allocation C++

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.

πŸ‘︎ 2
πŸ’¬︎
πŸ‘€︎ u/bootyfillet
πŸ“…︎ Jul 29 2018
🚨︎ report
[C] Are there any issues with large arrays/dynamic memory allocation (malloc) that a beginner should know?

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?

πŸ‘︎ 24
πŸ’¬︎
πŸ‘€︎ u/TheOneMerkin
πŸ“…︎ Jun 27 2014
🚨︎ report
[C] ELI5: Dynamic Memory Allocation

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?

πŸ‘︎ 4
πŸ’¬︎
πŸ‘€︎ u/tramsay
πŸ“…︎ Jan 02 2016
🚨︎ report
C++ practical use of dynamic memory allocation?

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?

πŸ‘︎ 7
πŸ’¬︎
πŸ‘€︎ u/Nihy
πŸ“…︎ May 05 2013
🚨︎ report
Procedural fireworks made in c++ using gradient fill and DIBs. The stars are a vector<class*> and each are allocated into dynamic memory. The class stores all the TRIVERTEX information as well as other properties including another vector<struct*> for all the individual points in each star. v.redd.it/nluooskbae971
πŸ‘︎ 21
πŸ’¬︎
πŸ‘€︎ u/DarkYearGamer
πŸ“…︎ Jul 05 2021
🚨︎ report
New and Delete Operators in C++ | Dynamic Memory Allocation | CPP Progra... youtube.com/attribution_l…
πŸ‘︎ 2
πŸ’¬︎
πŸ“…︎ Oct 17 2017
🚨︎ report
[C++] Dynamic memory allocation in binary search trees

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?

πŸ‘︎ 3
πŸ’¬︎
πŸ‘€︎ u/BinkyOinkasaur
πŸ“…︎ Nov 02 2014
🚨︎ report

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.