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 1 year ago.
Improve this question
typedef struct{
int x;
int y;
} Coordinate_T;
Coordinate_T *p;
p = (Coordinate_T *)malloc(sizeof(Coordinate_T));
p->x = 100;
p->y = 200;
free(p);
exit(0);
I'm trying to get the hang of pointers but it is really confusing when they are used like this. I got this code from a textbook and I'm supposed to find what's wrong with this code
Woo, it's been a long time since I dealt with C pointers, but let me see if I can help.
Coordinate_T *p;
declares a pointer to a Coordinate_T struct. We don't have any memory available yet, we just have a pointer to... nothing.
p = (Coordinate_T *)malloc(sizeof(Coordinate_T))
actually allocates the memory for us. Now p points to something useful where we can store values. "malloc" is shorthand for "memory allocation." It requires a size - how much memory do you need? "sizeof(Coordinate_T)" is an easy way to say "the size of this struct that I want to point to. Finally, the type cast "(Coordinate_T *)" tells the compiler "treat this like a Coordinate_T pointer".
p->x = 100;
p->y = 200;
Sets the x value of our newly-allocated struct to 100, and the y value to 200. The arrow notation (->) says "p is a pointer; inside the memory it points to, set..."
free(p)
frees the memory you just allocated with malloc(). This means we're done with it, the operating system can use that memory for something else. If you don't free memory when you're done with it, that's a "memory leak" - it's still marked as being in-use, and the operating system can't re-use it. In a long-running program, the leaked memory can build up and build up, and eventually the operating system kills the running program when no more memory is available.
exit(0);
just kills the program, and returns the value zero, which is the traditional value that means "Everything is fine." If a program returns any other value, that means some error occurred.
tl;dr: This program doesn't do much. It sets a couple values, then throws away the memory it used, and exits. It would be more interesting to include a printf() statement to echo those values back to you, but I'll leave that to you. ;-)
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().
This question already has an answer here:
Pointer to a specific fixed address
(1 answer)
Closed 3 years ago.
I am sorry I know that's super basic question but I have to ask.
I have an array in integer type and I want to Assign it to specific memory address. How can I do that with C language?
For Example ;
int inputs[10] ={4,10,89};
So I want to Assign this inputs to 0x20000001.
Thank you so much.
Unless you are managing your memory allocation regions, say with linker scripts or other means, you should not do it. Compiler takes care of all memory allocation for you and does not provide any means for pre-defined memory addresses.
However, if you know what you are doing, you can use a pointer to handle it:
int *array = (int*)0x2000000;
now you can initialize it element by element, or by memcpy.
memcpy(array, inputs, sizeof(inputs));
You are likely to get segfault due to memory access violation if you are accessing restricted area of the memory, but here's a quick code to test it out if you know what address you are writing to:
int address = 0x20000001;
int *ptr;
ptr = (int*) address;
*ptr = inputs;
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
I am writing a function in C. What I found is that when I debug in gdb, I found a pointer "result" has the same address with another pointer before "result" was declared. Part of my code:
char* stringSum(char* x, char* y){
puts(x);
puts(y);
printf("\n");
int lengthx=strlen(x);
int lengthy=strlen(y);
int lengths=MIN(lengthx,lengthy);
int lengthl=MAX(lengthx,lengthy);
char* s=((lengthx<=lengthy)?x:y);
char* l=((lengthx>lengthy)?x:y);
int returnSize=MAX(lengthx, lengthy)+2;//-----I could print result now
printf("before, short is : ");puts(s);
char* result=malloc(sizeof(char)*returnSize);//-----but result is allocated now
printf("after allocate memory for result, short is: ");puts(s);//---s is changed!
result[returnSize-1]='\0';
......
}
This function get the sum of two numbers (in string) so that I could calculate the sum of two large numbers. In gdb: I got this weird problem:
My problems are in red and yellow rectangles
(When debug in gdb) Before char* result=malloc(sizeof(char)*returnSize); I print s and result (so now it haven't been declared yet) and got
(gdb) print s
$5 = 0x61f950 "6597242170048699800240000000000"
(gdb) print result
$6 = 0x61f950 "6597242170048699800240000000000"
I couldn't understand that since how could an undeclared pointer points to an existing address? (This function is called by another function with a very large number of x and y (in string). If I changed them to relatively small values I will always get the right answer. What's more, if I create a new .c file and only have this function and main function, I will not have that problem anymore even with a large value.)
My second problem is that I have printed s twice and I found the second time I print (after declare the pointer result) s is changed! (Similar to the first problem, if I choose smaller values for x and y or create a new .c file, I will not have the same problem.)
I guess I have some problem with malloc but after search online I haven't find any useful resources will could help me solve the problem. Do I have the problem about memory management?
You have at least two serious problems with your code.
The first problem is that you never free what you malloc, creating sizeable memory leaks at each recursive call.
The second problem is that you are trying to assign strings, which doesn't have the effect you hope for.
Here is an example of what you do (comments mine):
// allocate some memory and assign its address to abcd
char* abcd=malloc(sizeof(char)*returnSize);
// throw it away by assigning a different value to abcd
abcd=karatsuba(stringSum(a,b),stringSum(c,d));
// then assign yet another different value to abcd
abcd=stringSubstract(abcd,ac);
// and another one
abcd=stringSubstract(abcd,bd);//ab+cd
// Code below overflows, because memory abcd is pointing to is
// not the original block allocated for it (you threw it away).
// It is a block allocated and returned by stringSubstract.
// Its length is not necessarily sufficient to accommodate all
// the data you are trying to stuff in it.
int labcd=strlen(abcd);
for(i=0;i<=(ns/2-1);i++){
abcd[labcd+i]='0';
}
abcd[lac+i]='\0';
You can verify that this is the case by running your program under valgrind. You will get error messages that indicate a buffer overflow just before the mysterious shortening of s. It all goes downhill from there.
In order to fix the problem, you may want to use strcpy instead of pointer assignment. Another way to fix it would be ditching the abcd = malloc(...) lines in the beginning of the function, and using realloc to make sure they have the allocations have enough size.
In addition you definitely want to fix the memory leaks. You need to call free for each variable you malloc after you're done with it. If you are returning a malloced variable, the caller needs to free it after using it.
This question already has answers here:
Why freed struct in C still has data?
(7 answers)
Closed 8 years ago.
int main(int argc, char **argv)
{
counter = 0;
int size = 5;
struct trie *mainTrie = malloc(size * sizeof(mainTrie));
test(mainTrie);
printf("%c", mainTrie[2].alphabet);
free(mainTrie->alphabet);
printf("%c", mainTrie[2].alphabet);
return 0;
}
The test functions was just to see how I can use malloc. My experiment was successful except one thing: free(mainTrie).
When I added printf("%c", mainTrie[2].alphabet) after I 'freed' the memory spaces, the output still gave me the same letter that was stored at mainTrie[2].alphabet from method 'test'.
Am I not understanding something? Thanks in advance...
Show us your complete code, specially the maintree struct. It seems like you need to free the maintree variable:
free(maintree);
However, freeing memory means that the piece of memory you reserved will be available to the O.S again. It doesn't mean you actually set that piece of memory tu NULL. Edit: #MattMcNabb "Typically the memory is not released to the OS, just made available for further allocations from the same process. (This depends on a lot of things of course)"
It is possible that you are printing a piece of memory that doesn't belong to your program anymore, but the data hasn't changed yet.
Note these 2 important things from the documentation
A block of memory previously allocated by a call to malloc, calloc or realloc is deallocated, making it available again for further allocations. (just deallocated, doesn't say anything about the values being changed)
If ptr does not point to a block of memory allocated with the above functions, it causes undefined behavior.
If ptr is a null pointer, the function does nothing.
Notice that this function does not change the value of ptr itself, hence it still points to the same (now invalid) location. (so you maybe pointing to a piece of memory you allocated in the past, but it still has the same values, it is possible, it wont happen all the time).
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 8 years ago.
Improve this question
Would you like to help me to understand the mechanism of "pointers" in C:
How does the program identify the end of an array, which was dynamically allocated and pointed at by a pointer (example: montext1)? Where are these arrays stored in RAM (probably not in data, not in stack, perhaps in the heap)?
A pointer is defined by a type and a size: how is this implemented in RAM for a dynamic allocation like in the example below?
#include <stdio.h>
char * gettext()
{
char *text;
printf("Text:");
scanf("%s", &text);
printf("\n");
return text;
}
int main()
{
char *montext1 = gettext();
char *montext2 = gettext();
}
Your program is very wrong, and has undefined behavior. So it's not a very good starting point for discussion.
There is no "dynamic allocation" in your program, only chaotic overwriting of random memory.
It should use heap allocation, i.e.:
char * gettext(void)
{
char *s;
printf("Text:");
fflush(stdout);
if((s = malloc(256)) != NULL)
{
if(fgets(s, 256, stdin) == NULL)
{
free(s);
s = NULL;
}
}
return s;
}
The caller must free() the returned string, and check for NULL before printing it.
The problem here is the CPU does not know the end of the data pointed to by a pointer. For the CPU it's just raw bytes in the memory which can be either application bytes or data entered by the user. However the compiled C code via the C std library know the string (char*) is supposed to end with a zero byte. That's how it knows where the end is.
But, in the gettext method: you need to allocate some memory too, via malloc (calloc), because in it's current stage your application is writing into memory which is not owned by it. And of course, the caller of gettext needs to free the memory.
And finally: a pointer is just an address in the memory, it points to some bytes. It is the role of the application to interpret those bytes in the proper way, such as identify zero terminated strings.
How does the program identify the end of an array, which was dynamically allocated and pointed at by a pointer
This is handled internally by the dynamic memory allocation library routines and it is handled differently on every implementation. The actual code could be in stdlib or it could be in an OS API. So how it is done depends on compiler and OS both.
Where are these arrays stored in RAM
If they were dynamically allocated, they were stored on the heap.
A pointer is defined by a type and a size
No, a pointer is a type, end of story.
how is this implemented in RAM for a dynamic allocation like in the example below
You linked no example containing dynamic allocation. The code you posted is nonsense code. It attempts to copy data into the address where you allocated a pointer. This doesn't make any sense, so the program will crash and burn.
If you rewrite the program so that scanf("%s", &text); is replaced by scanf("%s", text);, then you attempt to copy data into an uninitialized pointer's address, which is random. This is undefined behavior and will also cause your program to crash and burn.