Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I am making a game in c, and I get an error with a struct array which I have created.
typedef struct{
int type, level, x, y, w, h;
} Tile;
Tile *map[256];
Tile *t;
t->type = 0;
t->level = 0;
t->x = 0;
t->y = 0;
t->w = 0;
t->h = 0;
map[0] = t;
Once compiled, the program prints:
Segmentation fault (core dumped)
Defining a pointer does not automatically make that pointer to point to a valid memory location. A pointer, which is not allocated memory, is called as uninitialized pointer and cannot (shall we say, should not?) be de-referenced.
In your code,
t->type = 0;
and so on, you're de-referencing t which is not allocated memory. Hence, by de-referencing an unitialized pointer, you invoke undefined behavior. The segmentation fault is one of the many side-effects of the UB.
Solution: You need to allocate memory to t before you can actually dereference it. Maybe you can have a look at malloc() and family of functions to get the memory allocation done.
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
#include <stdio.h>
typedef struct {
int x,y;
} point;
point* create_point(int x,int y) {
point p={x,y};
point* ptr = &p;
return ptr;
}
int main() {
point* p1 = create_point(1,2);
point* p2 = create_point(6,7);
printf("%d, %d, ", p1->x, p1->y);
printf("%d, %d \n", p2->x, p2->y);
return 0;
}
When I compile with repl.it I get 6,7,0,0 as output but when I run the same program with sublime text editor, I get a different output : 6,7,6,7. Does anyone know why? and which output is the correct output? Any help is appreciated, thank you.
Generally, when you have a "factory" function that creates and returns a pointer to an object, the object should be allocated on the heap with malloc(), like so:
int *factory(){
int *p;
p = malloc(sizeof(whatever));
return p;
}
In C, function returns are by value. In this case, while p is a local, stack-allocated variable, it is a pointer and its value (which is what is passed back to the caller) will be the address of the heap-allocated object returned by malloc() so it is a meaningful value outside the scope of the function.
In your function create_point(), you're returning a pointer, but because p is a local (automatic) variable, it is allocated on the stack and so the pointer to it that you're returning will refer to an address that had been in create_point()'s stack frame. Depending on how a given compiler orders automatic variables on the stack (and what order you access them in) as well as other information it needs to place there per the ABI, it's possible that you might have gotten lucky and received the results you expected if you only called create_point() once, and you would have never detected this error. But the second call's stack frame is likely in the same position as or overlaps with the position of the first call's stack frame on the process's stack, meaning that some or all of the contents left over from the first call (since a function call's stack frame generally isn't cleared once the function returns, the old values will still be there until those memory locations are overwritten) would get clobbered by both the second call to create_point() as well as the subsequent calls to printf().
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
#define MAX_SPACES 10
#define MAX_SIMPLE_EVENTS 5000
#define MAX_USER_EVENTS 1000
struct {
EventSpace* p_spaces[MAX_SPACES];
SimpleEvent* p_simple_events[MAX_SIMPLE_EVENTS];
UserEvent* p_user_events[MAX_USER_EVENTS];
}* G_manager;
static void add_space(EventSpace* space){
static uint16_t index = 0;
(*G_manager).p_spaces[index] = space;
}
After running in gdb got:
Program received signal SIGSEGV, Segmentation fault.
0x0000000000400559 in add_space (space=0x7fffffffdf30)
How to impove it?
At least in the code you're showing, you haven't actually allocated the memory for the structure containing the arrays; you've only created a pointer. So when you dereference that pointer meaning to write into an instance of the structure, you hit a random memory address and got the relatively tame result of your program crashing.
You could change G_manager from a pointer-to-struct to an instance of the struct itself; or you can malloc a buffer big enough for the structure and assign that buffer to G_manager
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I am trying to write a C program in Linux.
#include<stdio.h>
void fun(int *r)
{
*r=20;
r--;
*r=30;
r--;
*r=40;
}
int main()
{
int a=2;
int b=3;
int c=4;
fun(&c);
printf("a=%d\nb=%d\nc=%d",a,b,c);
return 0;
}
When I run the code it gives me a segmentation fault (core dumped).
But when I print the addresses of a, b, and c in the main function before the function call the code works.
#include<stdio.h>
void fun(int *r)
{*r=20;
r--;
*r=30;
r--;
*r=40;
}
int main()
{
int a=2;
int b=3;
int c=4;
printf("a=%p\nb=%p\nc=%p\n",&a,&b,&c);
fun(&c);
printf("a=%d\nb=%d\nc=%d",a,b,c);
return 0;
}
Can anyone please tell me why this happened?
In your code, c is a single variable, and you pass the address of this variable to fun(). Later, inside fun() you try to move the pointer and then dereference it. It actually invokes undefined behavior.
Only the array elements are guaranteed to be allocated contiguous memory locations, separate variables can very well be allocated in compiler-dependent way.
You can define an array like
int a[3] = {0};
and then, call fun() like
fun(&a[2]);
and get the desired result in a well-defined way.
It may have something to do with whatever optimizations your compiler applies (or doesn't). This certainly is not portable code. If it works at all, that is by luck only, as C makes no guarantees about the order in which variables are allocated. This program seems to depend on undefined behavior.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
Consider the below code segment:
void f() {
int arr[10];
arr = malloc(sizeof(int) * 100);
for (int i = 0 ; i < 100 ; i++) {
printf("%d ", arr[i]);
}
puts("");
free(arr);
}
Will the original arr[10] stack memory be freed when the function f returns? (Or is this a stack memory leak?)
You cannot do
arr = malloc(sizeof(int) * 100);
like you've done (tried to do) in your code snippet. arr is array type and assignment is not permitted on that.
Subsequently, maybe worthy to mention, calling free() on a non-dynamically allocated pointer invokes undefined behavior.
FWIW, "leak" comes into picture for the memory allocated by the dynamic memory allocation (generally, heap). For variables allocated in "stack" area (by compiler) need not to managed (for de-allocation or free -ing) from your program.
int arr[10]; this array is already allocated from stack;
to allocate array dynamically declare it as a pointer
int *arr;
dynamic allocation will not be automatically freed, use free or similar to free it;
When you declare the array arr, you are already assigning space (on your function stack) to it. It doesn't make sense to make the malloc'd memory (which gets allocated on the heap) assigned to that array.You are invoking compile error doing that. You should have used a pointer instead of declaring that array. A pointer will grab and store that malloc'd space for you.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I have a doubt in de-referencing the pointers
I wrote a simple code but i dont know the reason why it is failing in certain condition can someone pls tell what is the reason for it to fail. and if we have char *ptr = "stack overflow" then the compiler itself will allocate memory to it.
int main()
{
int *ptr = 10;
double *dptr = 111.111
printf("%d", *ptr); //will give segmentation violation as we are trying to access the content in location 10
printf("%d", ptr);//o/p will be 10
printf("%lf", dptr); // will give segmentation violation
printf("%lf", *dptr); // will give segmentation violation
}
int *ptr = 10;
double *dptr = 111.111
The problem lie in the above two lines.
ptr points to the address 10 and dptr is I don't know where it is pointing.
Dereferencing these pointers will certainly yield undefined behavior.. usually a segmentation violation fault.
Fix:
int main(){
int iVal = 10;
double dVal = 111.11;
int *ptr = &iVal;
double *dptr = &dval;
printf("%d", *ptr); // ok
printf("%p", (void *)ptr);// ok
printf("%p", (void *)dptr); // ok
printf("%lf", *dptr); // ok
return 0;
}
Theory: A pointer is a variable that holds address - or as Alexey Frunze says:
The C standard does not define what a pointer is internally and how it
works internally. This is intentional so as not to limit the number of
platforms, where C can be implemented as a compiled or interpreted
language.
A pointer value can be some kind of ID or handle or a combination of
several IDs (say hello to x86 segments and offsets) and not
necessarily a real memory address. This ID could be anything, even a
fixed-size text string. Non-address representations may be especially
useful for a C interpreter.
When you do
int *ptr = 10;
you tell the compiler that ptr is a pointer to the address 10. Dereferencing this address will cause undefined behavior and may cause a crash.
You would most likely want something like:
int ival = 10;
int *ptr = &ival;
Similar for the double pointer.
char *ptr = "stack overflow"
This buffer was allocated in TEXT SEGMENT hence there is no issue of dereferencing and getting the address but if you modify the data content its a voilation [Segmentation Fault]
Note:-
Please refer from online,how many segments will be created for a program (process) ?
[Generally, Heap Segment,Stack Segment,Data Segment & Text Segment]
The reason char *ptr = "stack overflow" works and int *ptr = 10 does not is that 10 is just the number 10, but "stack overflow" evaluates to a pointer to the characters.
String literals are special kinds of constants. The compiler puts the characters of the string somewhere in memory, and the value of the string literal is a pointer to those characters. Conversely, integer and floating-point constants are just their values; they are not pointers.