Freeing malloc of unknown size

Freeing malloc of unknown size

By : Shree
Date : November 16 2020, 06:23 AM
With these it helps The only way is to keep track of the element count of the array, if you don't want to pass it to every function when passing the array, you can combine both pieces of information in a struct, like here
code :
#include <stdlib.h>

struct ArrayOfStrings
    int    count;
    char **data;

struct ArrayOfStrings get_moves()
    struct ArrayOfStrings result;
    char **moves;

    // some code

    result.count = 0;
    result.data  = malloc(sizeof(char *) * k); // 'k', could ranges between 1~9
    if (result.data == NULL)
        return result;
    result.count = k;

    moves = result.data;    
    for (int i = 0; i < k; i++)
        moves[i] = malloc(82);
        if (moves[i] == NULL) 
            /* also free succesfully allocated ones */
            for (int j = i - 1 ; j >= 0 ; --j)
        result.count = 0;
        result.data  = NULL;
        return result;
    // more code

    return result;

int main(){

    //some code
    struct ArrayOfStrings res = get_moves(some_input);
    //more code
    for (int i = 0; i < res.count ; i ++)
    return 0; // you should return from main.
sizeof(res) / sizeof(res[0]) == sizeof(char **) / sizeof(char *) == 1

Share : facebook icon twitter icon
is it true to do this to malloc array with unknown size

is it true to do this to malloc array with unknown size

By : zxgiot
Date : March 29 2020, 07:55 AM
it should still fix some issue This is absurdly false, full of memory leaks and undefined behaviors.
However, it's not that far from one of the right ways, the linked list way:
code :
struct linked_int
    int value;
    struct linked_int* pNext;

struct linked_int *pHead=NULL;
struct linked_int **ppTail = &pHead;
int* array = NULL;
int cpt=0;
/*Read file, building linked list*/
FILE *fp = fopen("/home/inputFile.txt","r");
if(fp != NULL)
    int var;
            struct linked_int *pNew = malloc(sizeof(struct linked_int));
            pNew->value = var;
            pNew->pNext = NULL;
            /*Append at the tail of the list*/
            *ppTail = pNew;
            ppTail = &(pNew->pNext);


/*Copy from the linked list to an array*/
array = malloc(sizeof(int) * cpt);
if(array != NULL)
    int i;
    struct linked_int const *pCur = pHead;
    for(i=0 ; i<cpt ; i++)
        arr[i] = pCur->value;
        pCur = pCur->pNext;

/*Free the linked list*/
while(pHead != NULL)
    struct linked_int *pDelete = pHead;
    pHead = pHead->pNext;
ppTail = &pHead;
int arrayCapacity=0, numberOfItems=0;
int* array = NULL;
int var;
while(fscanf(fp, "%d", &var)==1)
    if(numberOfItems >= arrayCapacity)
        /*Need to resize array before inserting*/
        const int MIN_CAPACITY = 4;
        const double GROWTH_RATE = 1.5;
        int newCapacity = arrayCapacity<MIN_CAPACITY ? MIN_CAPACITY : (int)(arrayCapacity*GROWTH_RATE);
        int* tmp = realloc(array, newCapacity*sizeof(int));
            /*FAIL: can't make the array bigger!*/
            /*Successfully resized the array.*/
            array = tmp;
            arrayCapacity = newCapacity;

    if(numberOfItems >= arrayCapacity)
        puts("Cannot add, array is full and can't be enlarged.");
        array[numberOfItems] = var;
/*Now we have our array with all integers in it*/
How to optimize malloc() or dynamically fill memory of an unknown size?

How to optimize malloc() or dynamically fill memory of an unknown size?

By : 0yy34qr6lu8
Date : March 29 2020, 07:55 AM
it helps some times I'm just playing around in C, and I wanted a function that would generate the Fibonacci Sequence up to a variable maximum term and be returned as a pointer to an array. The code below works just fine.
code :
int* fib = malloc(sizeof(int));   
    x = 1, y = 1;
    fibterms = 0;

    // same loop as above, but 
    // filling the array this time
        fib[fibterms] = x;
        int temp = x;
        x += y;
        y = temp;
        fib = (int *)realloc(fib , sizeof(int)*(fibterms+1));//fibterms is a int from 0
Freeing a malloc'd structure containing malloc'd strings

Freeing a malloc'd structure containing malloc'd strings

By : jwhiting81
Date : March 29 2020, 07:55 AM
fixed the issue. Will look into that further Since there are three malloc() calls used to build the object that you're passing ownership to:
code :
    wrapper_error_message_t *cErr = (wrapper_error_message_t *)malloc(structSize);

    cErr->severityLevel = 3;

    const char *errWhat = err.what();
    cErr->what = (char *)malloc((strlen(errWhat)+1) * charSize);
    strcpy(cErr->what, errWhat);

    const char errorType[] = "Library Exception Type Name 1";
    cErr->typeAsText = (char *)malloc((strlen(errorType)+1) * charSize);
    strcpy(cErr->typeAsText, errorType);
    return cErr;
    cErr->what = (char *)malloc((strlen(errWhat)+1) * charSize);
    strcpy(cErr->what, errWhat);
Freeing up struct created with malloc who's member also had a malloc

Freeing up struct created with malloc who's member also had a malloc

By : user2128571
Date : March 29 2020, 07:55 AM
fixed the issue. Will look into that further Yes, you need to free also vector->data, the rule is: one call to free per each call to malloc
if you are under C99, you can use flexible array members:
code :
struct cvector {
    unsigned int size;     // indicates number of element in the vector
    unsigned int capacity; // indicates length of the array
    int data[];            // array to store the actual data
cvector cvector_create() {
    cvector retval = malloc(sizeof(struct cvector) + (sizeof(int) * 8));
    retval->capacity = 8;
    retval->size = 0;
    return retval;
Call to malloc, unknown size

Call to malloc, unknown size

By : iMax-pp
Date : March 29 2020, 07:55 AM
I hope this helps you . What is your target platform? The getcwd() documentation here makes two important points:
Related Posts Related Posts :
  • C - Get pointer adress to string
  • how to start a function using a Struct?
  • Trying to tweak sscanf() to ignore \n and \t
  • How to find the inverse of a Rectangular Matrix in C using GSL
  • sizeof() showing different output
  • How to select/read/copy values after specific character in a string
  • Jump from bootloader generates exception
  • Array dropping values, picks up garbage
  • Swig: Syntax error in input(3)
  • multiple definition and making sure function is correctly written
  • MD4 openssl core dumped
  • Undefined-Behavior at its best, is it -boundary break? -bad pointer arithmetic? Or just -ignore of aliasing?
  • Why am i getting problem3.c:20:23: error: expected expression before ‘int’?
  • Right Justified Zero filled String in C
  • C Function with parameter without type indicator still works?
  • How to transmit data from an interrupt handler to an user application?
  • Why do I get the error "bash: ./a.out: Permission denied" when I execute a C program in Linux mint 15
  • syntax of sigchld and its declaration
  • error using g_idle_add() in C++, same thing works in C
  • why if else or nested if else are called single statement in C
  • How do I interpret this printf in C
  • load the functions of a shell script without executing it
  • Is FilterSendNetBufferLists handler a must for an NDIS filter to use NdisFSendNetBufferLists?
  • How to write to flash memory using inline assembly?
  • More Return Statements vs. More Indentation
  • How to show an image on a PictureBox from resource?
  • Having malloced some memory,I could't calculator the proper size of the memories I malloced.I don't know why
  • What is the main difference between integer pointer and character pointer?
  • Why are some functions declared extern and header file not included in source in Git source code?
  • what is the use of fflush(stdin) in c programming
  • Is it safe to return file File descriptor locally allocated from another function In C
  • Changing undefined values of an array
  • What does an empty parameter list mean?
  • using strtol on a string literal causing segmentation fault
  • Same structure objects memory overlap?
  • C-Linux-Any way to pass command "history" to Linux shell?
  • Using #define in defining string size C
  • How to use thread pool and message queues in Multithreaded Matrix Multiplication?
  • Can't find how to select path to run a C program
  • Automatic variable in C not initialized but given fixed value within loop
  • main() function defined without return type gives warning
  • Output of following code with integer, float, char variable
  • why buffer memory allocation error in opencl
  • Why am I getting this error during run-time?
  • Strange behaviour of the pow function
  • task in increment , decrement , printf() , why these are evaluated in this manner in C
  • 28 extra bytes in bss
  • Waiting for multiple events without polling
  • Why are my variables reporting as "undeclared identifier" when compiling?
  • Correct AddNode function but somehing happens when I printf
  • When I traverse in the splay tree, then now which one is root?
  • Data type conversion in Postfix evaluation
  • No output in terminal (Head First C)
  • Data writes over after realloc
  • function: findnextchar() doesn't work
  • Getting file-size property from Nautilus
  • Forward declare entities in C standard library?
  • Static array in C
  • Function signature indicates return type void*, but returns pointer of a different type
  • How do I measure time per thread in C?
  • shadow
    Privacy Policy - Terms - Contact Us © ourworld-yourmove.org