This question already has an answer here:
How to access a structures' members outside of its original function?
(1 answer)
Closed 6 years ago.
#include<stdio.h>
int * display();
main()
{
printf("\nHello\n");
int * a = display();
printf("%d", *a);
}
int * display()
{
printf("\n Hi \n");
int b = 10;
return &b;
}
Can anyone tell me how does memory allocation work in c?
I'm sure we can access the value of b(in this program), then why can't we access the address of it? I get an error (Segmentation fault).
What is the concept behind it?
I'm a beginner.
You shouldn't return pointer to an automatic local variable. It will no longer exist once function return and therefore will invoke undefined behavior.
You can allocate memory dynamically and then return pointer:
int * display()
{
printf("\n Hi \n");
int *b = malloc(sizeof(int));
*b = 10;
return b;
}
Related
This question already has answers here:
Changing address contained by pointer using function
(5 answers)
Closed last year.
# include<stdio.h>
# include<stdlib.h>
void fun(int *a)
{
a = (int*)malloc(sizeof(int));
}
int main(void)
{
int *p;
fun(p);
*p = 6;
printf("%d\n",*p);
free(p);
return(0);
}
In vs code this shows error because int *p is uninitialized and tells me to initialize the variable 'p' to NULL to silence this warning. But when I did that it compiled but showed segmentation fault, likely because I'm assigning 6 to the null address, so how do I fix this?
This function
void fun(int *a)
{
a = (int*)malloc(sizeof(int));
}
changes its own local variable (parameter) a. That is the function deals with a copy of the value of the passed pointer p
int *p;
fun(p);
The pointer p stays unchanged and uninitialized.
To make the program correct you need to change the code the following way
void fun(int **a)
{
*a = (int*)malloc(sizeof(int));
}
//...
int *p;
fun( &p);
Though in this case it would be better to declare and define the function like
int * fun( void )
{
return malloc(sizeof(int));
}
//...
int *p = fun();
if ( p )
{
*p = 6;
printf("%d\n",*p);
}
free(p);
This question already has answers here:
Returning Arrays/Pointers from a function
(7 answers)
Closed 4 years ago.
Can an array be returned from a function in C without using static?
int *func(int n)
{
int d[100];
int i=0,a;
while(n!=0)
{
a=n%2;
d[i]=a;
n=n/2;
i++;
}
return d;
}
You cant return array that created locally on the stack after exiting from function its not valid anymore. you need to use static array[100] or pointer and malloc memory for it
int *func(int n)
{
static int d[100];
int i=0,a;
while(n!=0)
{
a=n%2;
d[i]=a;
n=n/2;
i++;
}
return d;
}
UPDT:
d is created with automatic storage duration and references to it will become invalid once it leaves its declaring scope, i.e., when the function returns.
The static storage instructs the compiler to keep a local variable in existence during the life-time of the program instead of creating and destroying it each time it comes into and goes out of scope.
You will also can use dynamically allocate memory inside the function.
int *func(int n)
{
int *d = malloc(sizeof(int) * (100));
int i=0,a;
while(n!=0)
{
a=n%2;
d[i]=a;
n=n/2;
i++;
}
return d;
}
And dont forget to free allocated memory
This question already has answers here:
Is free() zeroing out memory?
(7 answers)
Closed 5 years ago.
int main()
{
int *p,*q;
p=(int *)malloc(sizeof(int));
*p=5;
free(p);
}
When I examine the memory address allocated to p after the execution of the free(p) statement, I observe that the memory content is 0. Is this the right behavior because I have read that free does not initialize the memory to 0?
The content of *p after free(p) returns is undefined. It may be 0, 42 or anything else.
#include <stdlib.h>
#include <stdio.h>
int main(void) {
int *p, *x;
p = malloc(sizeof(int));
*p = 5;
// the following will print "0x7fd0cac00350: 5" or similar
printf("%p: ", p);
printf("%d\n", *p);
free(p);
printf("%p\n", p); // won't change from before
printf("%d\n", *p); // UNDEFINED BEHAVIOR
}
This question already has answers here:
How to access a local variable from a different function using pointers?
(10 answers)
Closed 6 years ago.
I started studying pointers and I got in some trouble with the next code:
#include <stdio.h>
int * g()
{
int a = 10;
return &a;
}
void main()
{
int *p;
p=g();
printf("%d",*p);
}
It returns the error segmentation fault. core dumped
I would really apreciate any help. Have a nice day!
You are returning the address of a local variable. When you leave the function your code does not know this variable anymore, thus the segmentation fault.
You would have to give a pointer to this function as a parameter or dynamically create memory for this variable in the heap.
e.g.
void g(int* p) {
*p = 10;
}
int main() {
int a;
g(&a);
printf("%d", a);
return 0;
}
or
int* g() {
int* p = (int*) malloc(sizeof(int));
*p = 10;
return p;
}
int main() {
int* p;
p = g();
printf("%d", *p);
free(p)
return 0;
}
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I am writing a function to find a value in a hash table. Why is there a run time error each it reaches line 6? Please Help!
int* value = 0;
printf ("find return value: %d \n", find(keyList[i], value));
The above two lines are the function calls used in main.
int find( char *key, int *p_ans ){
int hashValue = hash(key);
entry* newTable = table[hashValue];
while (newTable != NULL){
if ((newTable -> key) == key){
*p_ans = newTable -> val; // THE ERROR LINE
return 1;
}
newTable = newTable -> next;
}
return 0;
}
You need to allocate the int outside the function; either on the stack or on the heap.
To allocate it on the stack, just do
int ans;
find(key, &ans);
To allocate it on the heap, do
int* p_ans = new int;
find(key, p_ans);
...
delete p_ans;
You are setting this:
*p_ans = newTable -> val; // THE ERROR LINE
for this you have to malloc, at p_ans, but your p_ans pointer is 0, which is obtained from 'value' variable, which points to 0, that is the issue
add this line:
value = (int *)malloc(sizeof(int));
Because p_ans == NULL. Change your call to one of these:
Stack
int value;
if (find(keyList[i], &value)) {
printf ("find return value: %d\n", value);
}
else {
printf ("not found\n");
}
Heap
int *value = malloc(sizeof(int));
if (find(keyList[i], value)) {
printf ("find return value: %d\n", *value);
}
else {
printf ("not found\n");
}
free(value);
The point is that you need to have a space allocated for an integer. If you have a local variable int value then you can pass its address and find will change the variable's value.
If you have int *value then you've got a pointer. This pointer needs to point to an int somewhere. malloc allocates space for an int value.
Writing int *value = 0 doesn't create an int with a value of 0, it creates an int pointer with a value of NULL (0 means NULL when used as a pointer value). You can't dereference this NULL pointers. If you call find(keyList[i], NULL) then p_ans == NULL, and *p_ans dereferences a NULL pointer and crashes your program.
If it still doesn't make sense, consider these two code snippets. The first one will crash. The second one will work. Do you see why?
// Bad
int *pointer = NULL;
if (find(keyList[i], pointer))
// Good
int value;
int *pointer = &value;
if (find(keyList[i], pointer))
It's because you pass a pointer to NULL. You don't have to actually declare a pointer to pass a pointer to a function, instead use the address-of operator &:
int value = 0;
printf ("find return value: %d \n", find(keyList[i], &value));
/* Using address-of operator here -------------------^ */