FAQ Database Discussion Community


Freeing a copy of a pointer to malloc'd memory in C

c,pointers,copy,malloc,free
Couldn't seem to find an answer to my question elsewhere. Consider the code: int *ptr = malloc (sizeof (*ptr)); int *dummyPtr = ptr; free (dummyPtr); printf ("ptr: %p, dummy: %p\n", ptr, dummyPtr); As I understand it, free() takes in a pointer and makes it point to NULL aka (nil). I.e.,...

Invalid free() / delete / delete[] / realloc() error in assignment operator

c++,valgrind,free
I am new to programming and when I am trying to run a program using Valgrind I was getting an error like this. I googled hours to solve this problem. please can you tell me where I am going wrong. Hope there is some mistake near assignment operator. Error: ==5130==...

Should free() been called after longjmp()?

c,memory-leaks,malloc,free,longjmp
In this simple code should I take care about memory freeing in default case to escape from memory leak or can I use allocated memory? Does longjmp also revert memory allocations? #include <setjmp.h> #include <stdlib.h> #include <stdio.h> int main(int argc, const char* argv) { jmp_buf jmpbuf; int *p=NULL; switch(setjmp(jmpbuf)){ case...

Memory corruption (double free) on class destruction

c++,destructor,free
Would anyone please explain this case: why I am facing 'double free' problem in this simple code? void Rreceive (myclass){} int main () { myclass msg (1); Rreceive(msg); return 0; } where myclass is: class myclass { private: HeaderType header; byte * text; public: myclass(int ID); ~myclass(); HeaderType getHeader(); byte...

Random double free or invalid next_size

c,malloc,size,free
So I'm having a problem right now with my program (well, more with the shared library I've written). I'm trying to implement a TCP/IP stack, and am currently trying to implement ARP. ARP works, both resolution and replies, however my ARP Server will randomly crash (sometimes running for 10-20min, being...

Printing a line read from a file containing a particular word

c,pointers,file-io,printf,free
#include <stdio.h> #include <stdlib.h> #include <string.h> int main() { int i, p=0;; int c; char file_name[100]; char search[10]; printf("Enter the file name:"); scanf("%s", file_name); printf("Search word:"); scanf("%s", search); FILE *f = fopen((strcat(file_name, ".txt")), "rb"); fseek(f, 0, SEEK_END); long pos = ftell(f); fseek(f, 0, SEEK_SET); char *bytes = malloc(pos + 1);...

Do I have to pay for Google Endpoints?

servlets,free,google-cloud-endpoints
I'm thinking of using the Google Endpoint service to add some simple features on my Android app. Following a tutorial on Github (https://github.com/GoogleCloudPlatform/gradle-appengine-templates/tree/master/HelloWorld) I managed to create a very simple servlet with basic code and that's all I need. But it's not clear if I'll have to pay at some...

Is free() zeroing out memory?

c,gcc,memory-management,clang,free
Until today I lived in belief that calling free() on memory space releases it for further allocation without any other modifications. Especially, considering this SO question that clearly states that free() DOESN'T zero out memory. Yet, let's consider this piece of code (test.c): #include<stdlib.h> #include<stdio.h> int main() { int* pointer;...

Conflicting types for “free”

c,pointers,memory-management,compiler-errors,free
I'm getting the error Conflicting types for 'free' on the call to free() function below. int main ( ) { char fx [] = "x^2+5*x-1"; node * fxNode = buildTree(fx, sizeof(fx)/sizeof(char)); printf(deriveFromTree(fxNode)); // Should print "2*x+5" free(fxNode); return 0; } Can't figure out why. Not sure if this matter, but...

c free() works when I call but not in my function

c,memory,malloc,free
I am learning C and I am playing with malloc and free. But for some reason when I use free() in the main everything works but when I put it in my function it does not #include <stdlib.h> #include <stdio.h> struct st { int number; }; void del(struct st *s)...

C Memory management with int pointer (array)?

c,pointers,memory,malloc,free
Simple question, but the other similar questions on here are don't deal with this specific case, or so i could find. int * moves; moves = malloc(540); //540 is the most i will ever need, usually less someFunctionThatFillsSomeOfThoseSlots // also returns how many slots were used int * final =...

How can I deallocate my memory? [duplicate]

c,malloc,free
This question already has an answer here: How will you free the memory allocated? 2 answers I'm using malloc and I should do free but I'm a beginner in C and I didn't write a call to free before. This is the code if((new_str = malloc(strlen(token2)+strlen("/less")+1)) != NULL) {...

Does the struct get freed this way in C?

c,pointers,struct,free
I have the following struct which I use to implement a priority queue struct q_element { //Declaration of struct members int element; int priority; struct q_element *next_element; }; and I use a pointer to a struct 'cur' to start from the first item in the queue struct q_element* cur =...

Destroy an object with variables (free memory)

c++,object,memory,delete,free
I am trying to create an event/date orginaizer in C++. The overview is like a calender show one month and every Day in this calender is an Object (type: EventCell) The class EventCell stores the events for his day in a vector (name: eventData with type: "EventInfo": class for storing...

double free or corruption error on free

c,malloc,free,memcpy
this is the piece of code i use to create my char array on heap int currentArraySize = 10; char **finalArray = malloc(sizeof(char*)*currentArraySize); char buf[6] = "hello"; for(int b=0; b<currentArraySize; b++ ) { char * tmpString = (char*)malloc(sizeof(char)*6); //copy the contents of buf to newly allocated space tmpString strncpy(tmpString,buf,6); finalArray[b]...

Cannot free fileName char * after fclose

c,memory-management,malloc,free,realloc
I am trying to free my file name (char * pointer) but got an error : Heap corruption detected: after normal block (#65) at 0x.... The code: static FILE *initializeIndexFile(char *database, char **indexFileName) { FILE *file1_p; *indexFileName = NULL; int len = strlen(database); *indexFileName = (char *)malloc(len *sizeof(char) + 1);...

Not sure how to use malloc() and free() properly

c,pointers,memory-management,malloc,free
int listLength(struct node *r) { int *len = (int *)malloc(sizeof(int)); if(!r) { free(len); return *len; } while(r) { r = r->next; *len += 1; } free(len) return *len; } I wrote this function to calculate the length of the linked list. I am still learning pointers by playing with them....

Free list implementation not working properly

c,malloc,free
So, I have been assigned a task to implement a free list. A list where items that are going to be free:d are added to and later the list is free:d in one go. I have written the following: #include <assert.h> #include <stdio.h> #include <stdlib.h> typedef struct list_t list_t; struct...

Memory leaks with nested struct types and copy functions in C

c,struct,nested,malloc,free
I have a problem with nested structs and their dedicated copy functions. The structure of the types is as follows: There is one Data instance in the program Every Problem instance contains a pointer to the Data instance Every Bigproblem instance has it's own Problem instance. Thus, when a BigProblem...

c - getting a heap error when trying to free

c,pointers,malloc,free,strcat
This smells like a heap corruption of some kind but I can not seem to find it. the problem occurs on string_utils_replace() when trying to run free(tmp_for_free). the function is supposed to replace every occurrence of "search" with "replace" in "string". char* string_utils_part_of_string(char *string, int from, int to) { int...

malloc and free in .h and .c while using language c

c,malloc,free
I'm new to C programming and I'm really confused about malloc() and free(). I need to read some random number of random data values from file (.yaml) and store them in hashmap, something like < char *key_name, char *type, void *value >. I'm using void * pointer to store any...

When to free a dll after exporting object

c++,c,dll,free
i am exporting a function from a dll the following way: extern "C" __declspec(dllexport) carsim::ICar* __cdecl createCarPlugin() { return new CarPlugin(); } In my main-Program I explicitly load the dll to extract this method. The declaration of the interface ICar is recognized by both - the dll and the main-program:...

Unable to properly free malloc of another malloc [duplicate]

c,malloc,free,dynamic-memory-allocation,calloc
This question already has an answer here: String assignment in C 4 answers Here's the snippet with issues. int main() { char** RESERV = (char**)malloc(sizeof(char*)*4); printf("%i, %i, %i, %i, %i", **RESERV, *RESERV, RESERV, &**RESERV, sizeof(char*)); int i; for(i = 0; i < 4; i++) { RESERV[i] = (char*)calloc(sizeof(char),16); RESERV[i][15]...

shallow copy struct got weird result on Xcode

c,malloc,free,dynamic-memory-allocation,shallow-copy
the code here is a typical example for shallow copy, it ought to got the warning when running, but on my Xcode, its running well and result is hi,hihi,hi why? The code: struct pc { char *p; }; int main() { struct pc pc1; pc1.p = malloc(100); strcpy(pc1.p, "hi"); struct...

Calling free() causes my program to crash

c,crash,printf,malloc,free
I'm having a really weird issue where trying to call free on an allocated piece of memory causes my program to crash. Here's the relevant code: int i, count; char *specifier; char aisle[1]; count = 0; /*Find name of the new item and assign to the name field of new_node...*/...

Free up more Inactive or File Cache memory in Activity Monitor

ios,objective-c,osx,memory,free
I have found a application has Clean Memory function. I think it uses the original PURGE function, but after checking (using Activity Monitor), I see that it's likely to be more free File Cache than Purge command (or it can operate independently of the PURGE command). Please refer my experiment...

Deallocating 2D array in C

c,arrays,malloc,free
For whatever reason I am getting the following error when trying to free the 2D array I created: Error in `./a.out': free(): invalid next size (fast): 0x0000000001759310 *** Aborted (core dumped) I printed out the contents of the array and they are correct and I am able access all of...

HTTP client with free(): invalid pointer error while freeing contents of char **

c,arrays,http,pointers,free
I've looked all over for solutions to this problem but tools like Valgrind and GDB are not helping me. Valgrind doesn't even finish running the program and GDB just tells me information that contradicts itself. I have an HTTP client that allocates a list of strings from the headers retrieved...

What is the correct way of use free() in C structure

c,list,memory,free
I've a little confusion with structs and free operation in C. I have to use this struct ( I know is no best idea define *tList instead of tList but it must be that way) typedef struct cel{ int elto; struct cel *bif; struct cel *next; } *tList; bif point...

malloc and free in C

c,free
if I have something like struct Node *root; struct Node *q; root = malloc( sizeof(struct Node)); q = root; free(q); is the node q is pointing to freed?? or would I have to pass root to the free function?...

Does freeing a pointer which was assigned to another pointer of another type (allocated by `malloc`) invoke Undefined Behavior?

c,pointers,memory,free,undefined-behavior
The title maybe confusing. Suppose str is a pointer allocated by malloc. ptr, of type int*, is assigned to it and is freed as shown by the code snippet below: char* str = malloc(64); int* ptr = str; free(ptr); I've tried to compile the above code. It just gives a...

Allocating space for upper triangular matrices in algebraic notation

c,matrix,malloc,free,algebra
I'm working on a project (written in C) involving matrix factorization and I need some help. My objective is to allocate memory for an upper triangular matrix and I want to access it via algebraic row and column notation (i.e. i,j in {1,2,...,n} instead of i,j in {0,1,...,n-1}). For example,...

segmentation fault after memcpy and free

c,segmentation-fault,free,memcpy
I a new C programmer. I try to remove one element from a static array and copy the rest on a dynamic array. The program worked fine but after free() I get a segmentation fault. I think that the pointer temp is pointing to some memory on stack that's why...

malloc and free in linux aborted [closed]

c,linux,malloc,free
I have a big C program (64bit), it uses a lots of malloc function call. When I run it in Visual Studio or in Windows platform it works fine. But when I try to run it in Linux I have a problem with malloc() and free(). It is aborted while...

C: free() for row of 2d int array makes program halt

c,arrays,memory,numpy,free
I am relatively new to C and have coded (or more precise: copied from here and adapted) the functions below. The first one takes a numpy array and converts it to a C int array: int **pymatrix_to_CarrayptrsInt(PyArrayObject *arrayin) { int **result, *array, *tmpResult; int i, n, m, j; n =...

set pointer to NULL after free the heap memory [duplicate]

c,memory-management,malloc,free
This question already has an answer here: Setting variable to NULL after free 21 answers I saw a simple C program: //create a pointer to 3 bytes on heap char *start = malloc(3); *start = 'u'; *(start + 1) = 'v'; *(start + 2) = 'w'; printf("%s has %zu...

C to Java code different output [closed]

java,c,numbers,free,square
i converted my C code to java but it outputs a different answer. Here is my C code. #include <stdio.h> #include <conio.h> int main () { int i, j, k; for (i=1; i<=59; i++) { k = 1; for (j=2; j<i; j++) if (i % (j*j) == 0) k =...

free memory used to return value in C

c,memory-management,return,malloc,free
I have a function that calls another function which creates a unique ID and returns it as a string by malloc(). my question is how do I free the memory once outside the function? or what is the better way to do what I would like to do. my function...

Why the value of root is printed as 0 in main function?

c,pointers,malloc,free
#include <stdio.h> #include <stdlib.h> struct nodeTree { int data; struct nodeTree* left; struct nodeTree* right; }; struct nodeTree* insertRoot(struct nodeTree** root, int data) { if(!(*root)) { struct nodeTree *temp = malloc(sizeof(struct nodeTree)); if(!temp) { exit(-1); } temp->data = data; temp->left = 0; temp->right = 0; (*root) = temp; free(temp); return...

C: free() invalid pointer; without changing address

c,free
I'm using C (not C++) and getting the following error: Error in './c_rk4': free(): invalid pointer: 0x0000000000a911c0 I was able to trace the error back to the lines (1) and (2). The error in (1) does not occur, if I comment out the line I marked. All other free() usages...

How to free memory occupied by a Tree, C?

c,tree,free
I'm currently dealing with a generic Tree with this structure: typedef struct NODE { //node's keys unsigned short *transboard; int depth; unsigned int i; unsigned int j; int player; int value; struct NODE *leftchild; //points to the first child from the left struct NODE *rightbrothers; //linked list of brothers from...

How to free allocated memory in a binary tree in C

c,tree,malloc,binary-tree,free
I am having trouble with a function in my C program. The purpose of the program is to: Read integers from a binary file into an array Sort these numbers using a binary tree Do some other stuff Free all memory that you allocated using malloc(); I've got everything working...

dynamic memory struct: free() failed w/ invalid size

c,struct,free,dynamic-memory-allocation
I have a C program that allocates memory for a structure and then free it. However, when I try to free the char array inside the struct, I get invalid size/pointer error. I am sure the structure is working fine because I checked by print out the context inside the...

HeapValidate Fails

c,pointers,malloc,free
I'm trying to build up a structure like this typedef struct elements { struct elements *next; int key; struct value *val; }; typedef struct dict { struct dict_elements **dictionary_head; }; typedef struct value { int val; }; The structure is created like this box->dictionary_head = (struct elements**)malloc(sizeof(struct elements*) * DICT_SIZE);...

Why free() impact other variable's value?

c,free
Practice for "Distinct Subsequences" online: Given a string S and a string T, count the number of distinct subsequences of T in S. A subsequence of a string is a new string which is formed from the original string by deleting some (can be none) of the characters without disturbing...

Cannot encrypt text twice with own encrypt function

c,while-loop,malloc,free
This is my program to encrypt a string: #include <stdio.h> #include <stdlib.h> #include <string.h> #define MAX 255 char * encrypt(const char *c, int key){ char *tmp = malloc(strlen(c)+1);; for(int i = 0; c[i] != '\0'; i++){ tmp[i] = c[i]+key; } return tmp; } int main(void){ char *dec = malloc(MAX); int...

C++ Error in ' ' : free(): invalid pointer

c++,templates,free,abort
I've read through similar problems, but I can't find anything that specifically addresses my problem (or I simply don't understand the other solutions) I am trying to implement a template Stack class, and am having an issue when trying to push to the stack. here is my Stack.cpp: #ifndef _STACK_H...

How will you free the memory allocated?

c,memory-management,malloc,free,dynamic-memory-allocation
I need to free some memory allocated on my program. Can I use something to clean the memory when I need it ? #include<stdio.h> #include<stdlib.h> #define MAXROW 3 #define MAXCOL 4 int main() { int **p, i, j; p = (int **) malloc(MAXROW * sizeof(int*)); return 0; } ...

free() and mxFree() in MATLAB - freeing memory twice

matlab,memory-management,free,mex
Good day, I have the following code which has given me problems for a day already. I have debugged it, and it works fine until trying to free the memory. The free() function should be called at the end of the execution automatically, so I commented the mxFree() code out,...

C - What does free() do to the memory?

c,malloc,free
I recoded malloc() free() and realloc(). I have a linked list with the pointers returned by malloc(). The question is : what does free() really do ? Currently, I did a memset() to have the same behavior of free(). But was it better just to set a flag in my...

free causing different results from malloc

c,string,malloc,free
Below is a C program i have written to print different combination of characters in a string. This is not an efficient way as this algorithm creats a lot of extra strings. However my question is NOT about how to solve this problem more efficiently. The program works(inefficiently though) and...

Freeing array of dynamic strings / lines in C

c,string,sorting,malloc,free
I am writing a program that is sorting the lines from the input text file. It does its job, however I get memory leaks using valgrind. #include <stdio.h> #include <stdlib.h> #include <string.h> char* getline(FILE * infile) { int size = 1024; char * line = (char*)malloc(size); int temp; int i=0;...