42426

free memory outside a void function where it is allocated

Question:

I have a void function

void foo(int *ptr) { //trying to allocate memory to hold 5 ints ptr = malloc(sizeof(int)*5): //I loop ptr and assign each with a value i =0 to 4; }

In the main function I have this lines

int main() { int *num; //I called the function foo(&(num)); free(num); return 1; }

I get munmap_chunk() invalid pointer error. I did try to dig in more information, but I could not figure this out. I know it will be basic for those who work in c. I was thinking I am passing by reference and it should work, but it is not. I am new to C, and so far has been a headache.

Answer1:

ptr is a local variable, his lifetime ends with the function, you need a pointer to pointer in order to alter num in main

void foo(int **ptr) { //trying to allocate memory to hold 5 ints *ptr = malloc(sizeof(int)*5); //I look ptr and assign each with a value i =0 to 5; }

Answer2:

For starters the function foo is declared like

void foo(int *ptr); ^^^^^^^^

that is its parameter has type int *. While you are calling the function like

foo(&(num)); ^^^^^^

where its argument has type int ** because the variable num is declared like

int *num;

The compiler should at least issue a message that the types are not compatible.

You need to define the function the following way

void foo(int **ptr) { ^^^^^^^^^ //trying to allocate memory to hold 5 ints *ptr = malloc(sizeof(int)*5): ^^^^ //I loop ptr and assign each with a value i =0 to 4; }

In this case the function call will be correct and as the original pointer is passed by reference it will be changed after calling the function.

As for the original function definition

void foo(int *ptr) { //trying to allocate memory to hold 5 ints ptr = malloc(sizeof(int)*5): //I loop ptr and assign each with a value i =0 to 4; }

then its parameter is a local variable of the function that keeps a copy of the argument. Any changes of the local variable that is of the copy of the original argument does not influence on the original pointer itself. After exiting the function the local variable (parameter) ptr will be destroyed.

Recommend

  • CRASH: *** -[__NSArrayM objectAtIndex:]: index 4294967295 beyond bounds [0 .. 9]
  • Redshift Querying: error xx000 disk full redshift
  • Thread 1: EXC_BAD_ACCESS (code =1 address = 0x0)
  • DIV instruction jumping to random location?
  • Object and struct member access and address offset calculation
  • How to assign byte[] as a pointer in C#
  • CakePHP ACL tutorial initDB function warnings
  • uniform generation of points on 3D box
  • SharedPreferences or SQLite Database?
  • why overloaded new operator is calling constructor even I am using malloc inside overloading functio
  • Exception “firebase.functions() takes … no argument …” when specifying a region for a Cloud Function
  • Q promise. Difference between .when and .then
  • Using variable in a value field in jMeter
  • R - Combining Columns to String Based on Logical Match
  • Get one-time binding to work for ng-if
  • JavaScriptCore crash on iOS9
  • Running a C# exe file
  • Can I have the cursor start on a particular column by default in jqgrid's edit mode?
  • Do create extension work in single-user mode in postgres?
  • Rearranging Cells in UITableView Bug & Saving Changes
  • Why winpcap requires both .lib and .dll to run?
  • R: gsub and capture
  • Numpy divide by zero. Why?
  • Circular dependency while pushing http interceptor
  • jqPlot EnhancedLegendRenderer plugin does not toggle series for Pie charts
  • Comma separated Values
  • Linker errors when using intrinsic function via function pointer
  • How to set the response of a form post action to a iframe source?
  • Hits per day in Google Big Query
  • FormattedException instead of throw new Exception(string.Format(…)) in .NET
  • Linking SubReports Without LinkChild/LinkMaster
  • Are Kotlin's Float, Int etc optimised to built-in types in the JVM? [duplicate]
  • unknown Exception android
  • XCode 8, some methods disappeared ? ex: layoutAttributesClass() -> AnyClass
  • Django query for large number of relationships
  • Why is Django giving me: 'first_name' is an invalid keyword argument for this function?
  • How can i traverse a binary tree from right to left in java?
  • How can I use `wmic` in a Windows PE script?
  • How to push additional view controllers onto NavigationController but keep the TabBar?
  • How to load view controller without button in storyboard?