This question already has answers here:
How do I modify a pointer that has been passed into a function in C?
(7 answers)
What happens to memory after free()?
(4 answers)
Unable to check memory allocation size with sizeof() [duplicate]
(2 answers)
Closed 2 years ago.
Can someone tell me, why I can't allocate memory to the struct array through the init() function? When done manually in main, everything is fine. When trying it through init() nothing happens (Also no error message). The adress is always 0x0, I guess the null pointer.
#define GAMES 100
typedef struct{
double *scores;
}SCORES;
void init(SCORES *arr);
int main(){
SCORES *numbers = NULL;
init(numbers);
printf("Adress is: %p\n", numbers); //Still 0x0
return 0;
}
void init(SCORES *arr){
arr = (SCORES*) malloc(GAMES * sizeof(SCORES));
}
Trying it with the code below works for malloc. I get an adress but if I use free(), memory is still allocated.
void init(SCORES **arr){
*arr = (SCORES*) malloc(GAMES * sizeof(SCORES));
}
...
init(&numbers);
...
free(numbers);
In the first code snippet you're passing the value of the numbers variable. In the function you change a local variable, and doing so has no effect on the variable is the calling function.
In the second snippet you correctly pass the address of numbers so it can be set in the function, and the call to free is also correct. Just don't attempt to use the value of numbers after you free it, otherwise it's undefined behavior.
Related
This question already has answers here:
Why do these pointers cause a crash?
(5 answers)
Closed 4 years ago.
int main()
{
struct stuff
{
int num;
}*foo;
// If I comment the line below, I get core dump error.
// Why?
foo = (struct stuff *)malloc(sizeof(struct stuff));
(*foo).num = 7;
printf("%d\n", (*foo).num);
}
You are only allowed to dereference a valid pointer.
In your case, foo being an automatic local variable, unless initialized explicitly, contains some indeterminate value, i.e, it points to an arbitrary memory location, which is pretty much invalid from the point of your program.
In case, you do not assign a valid pointer to foo (returned by malloc(), for example), foo points to some indeterminate memory location and attempt to dereference it will invoke undefined behaviour.
Segmentation fault is one of the side effects of UB.
foo is a pointer, it must point to address
If you dont want to use malloc you can do follow it:
struct stuff _foo;
foo = &_foo;
(*foo).num = 7;
foo in your example is an uninitialized pointer to a struct you just defined. If you doesn't initialize with a valid memory chunk it will always result in SEGFAULT. Another bad thing with your code is that even if you allocate memory for it, than you don't free it.
If you don't want to use malloc just make it local variable:
int main()
{
struct stuff
{
int num;
}foo;
foo.num = 7;
printf("%d\n", foo.num);
}
This question already has answers here:
Why don't I get a segmentation fault when I write beyond the end of an array?
(4 answers)
Closed 4 years ago.
Behold the following code:
#include<stdio.h>
void function ();
int main()
{
int * a;
*a=9;//this is supposed to give error as I am trying to
// dereference an unallocated pointer
// but it does not
printf("%d",*a);
function();
}
void function()
{
int * a;
*a=9;//this gives an error as I am trying to
// dereference an unallocated pointer
printf("%d",*a);
return;
}
Output is 9 and then the program crashes...
Why?
The difference for main() and function()
For main() we declare a pointer type then without the use of calloc or malloc is it by default allocated memory?
You either got lucky with the uninitialized data, or your compiler is optimizing the pointer away.
When you do a thing like that with
int *a;
*a = 9;
printf("%d\n", *a);
The compiler can just turn that into
puts("9");
Because it can know and see all of the values.
That's probably why your function call version crashes. Because the compiler has to generate a function that can be called by other code modules.
This sort of thing will vary a lot based on compiler, compiler version, and of course the flags given to the compiler.
This question already has answers here:
Can a local variable's memory be accessed outside its scope?
(20 answers)
Closed 5 years ago.
I've a question about var scopes and pointer.
That's an example function:
int *double(int a)
{
int p = a*2;
int *ret = &p;
return ret;
}
And that's the question:
After a fuction return to the caller, it should delete from the memory every variable declared in it.
In this function I only return the addres of "p" (that's declared only in the function) but when I use it in the main, for example, the space of memory allocated by the function "double" hasn't been deleted.
Why?
The memory isn't valid anymore; what happens when you access it after double has returned is undefined behavior. That means that anything is possible:
It could be that the value hasn't been overwritten by something else yet (what likely happened in your case).
It could be that something else has written something to that address, so the value is now random garbage.
It could be that your code opens up a wormhole to a parallel dimension, causing an invasion of evil space octopi that dooms us all.
So, basically, I don't recommend it.
This question already has answers here:
Can a local variable's memory be accessed outside its scope?
(20 answers)
Closed 6 years ago.
I don't understand why the following C code works (prints '53'). I thought that int a would be placed on the stack and wiped away as soon as foo() exits. If the compiler is instead placing int a on the heap, is there a way to tell it not to?
#include "stdio.h"
int * foo()
{
int a = 53;
int * b = &a;
return b;
}
int main(void)
{
int * c = foo();
printf("%d\n",*c);
return 0;
}
The integer a is stored on the stack. The reason this works is that function foo returns the address of a and function main dereferences this address to print it before the contents of a's address are overwritten. This program works by accident in this instance. If you want to preserve the value of a for the life of the program you'll either need to apply the static qualifier to a's declaration, or allocate a on the heap.
This question already has answers here:
Is an array name a pointer?
(8 answers)
Closed 9 years ago.
I am really confused in arrays and pointers.
Please tell me What is difference between following two codes?
int main()
{
int i,*p;
for(i=0;i<5;i++)
{
p[i]=i;
printf("%d",p[i]);
}
return 0;
}
int main()
{
int i,p[5];
for(i=0;i<5;i++)
{
p[i]=i;
printf("%d",p[i]);
}
return 0;
}
First one results in undefined behaviour.
For not having UB you need to allocate memory using either malloc or calloc.
Allocating memory will store the data in heap. After you done with your task , you need to free the allocated memory also.
Second one do not result in UB. it stores the array data in stack and not on heap.
Memory is automatically freed from stack once the scope is over.
In first p points to garbage location (not-allocated), and I'm pretty sure that in the way you are using it will generate a segmentation fault. You should allocate memory first, before using it, like:
p = malloc(5 * sizeof(int))
Second is allocated on stack and have the lifetime of the scope it is declared in.