This question already has answers here:
Crash or "segmentation fault" when data is copied/scanned/read to an uninitialized pointer
(5 answers)
Closed 5 years ago.
i tried coping a string to a pointer using strcpy. it causes a segmentation fault.any reason for that.
#include <stdio.h>
#include <string.h>
int main()
{
char *str=NULL;
strcpy(str,"C-DAC");
printf("%s\n",str);
return 1;
}
WHere does your string point to? Nowhere!
That's why you have segmentation fault. You have to either allocate variable on stack as array or define it as pointer and later allocate memory using malloc. When using malloc, don't forget to include "stdlib.h"
Either do this:
char str[6];
strcpy(str,"C-DAC");
or
char *str=malloc(sizeof(*str) * 6);
strcpy(str,"C-DAC");
Computer memory is divided into different segments. A segment for the operating system, for code, for local variables (called a stack), for global variables. Now you are initializing a pointer to NULL which means that the pointer str is now pointing to address 0. That address is simply not available for your program, it's meant for the operating system. In order to protect your system when you try to write that area your program is halted.
Related
This question already has answers here:
Using pointer after free()
(6 answers)
C - Accessing data AFTER memory has been free()ed?
(2 answers)
Accessing a freed pointer, shouldn't output be a segmentation fault?
(2 answers)
Closed 2 years ago.
I'm freeing a variable I allocated using malloc, but after I've freed it I try to access it and it still works fine.
I would expect a segmentation fault when accessing this memory but I dont get one.
Here is a simple example to show the problem:
#include <stdio.h>
#include <stdlib.h>
int main() {
int *arr = (int*)malloc(5*sizeof(int));
arr[0] = 2;
arr[4]=9;
free(arr);
printf("%d\n",arr[4]);
return 0;
}
The output is 9.
I am sorry to say, the problem seems to be that you expect a segmentation fault.
The C language standard doesn't require a segmentation fault. Once you access a freed pointer anything can happen - including nothing.
Most likely, the memory allocator cached the memory for re-use instead of returning the memory to the system. This way, in case you would need to allocate memory again, the second allocation would be faster.
This means that, from a system's point of view, your program still "owns" that memory.
From an allocator's point of view, that memory is owned by the allocator and you shouldn't use it (the allocator might write its own data over there).
From your program's point of view you have a quite bug.
This question already has answers here:
Writing to pointer out of bounds after malloc() not causing error
(7 answers)
Closed 2 years ago.
Malloc function in C allocates the size of memory passed into it's argument in bytes.
Here my struct variable has two integer values.So size of struct should be 8 bytes. I am only allocating 1 bytes and it's still working.
Why?
C (gcc)
#include <stdio.h>
#include <stdlib.h>
struct node{
int a;
int b;
}ab;
int main(){
struct node * nl=(struct node *)malloc(1); //I am allocating memory here
nl->b=89;
nl->a=45;
printf("%d %d %ld",nl->a,nl->b,sizeof(int));
}
Try it online!
When you write past the end of allocated memory, you invoke undefined behavior, which means you can't reliably predict what the program will do. It could crash, it could output strange results, or (as in this case) it can appear to work properly.
How undefined behavior manifests itself can change by making a seemingly unrelated change, such as adding an unused local variable or adding a call to printf for debugging. It could also change by compiling with different optimization settings or with a different compiler.
Just because the program could crash doesn't mean it will.
On most architectures, memory is allocated in 4k "pages" and no smaller. Malloc is placing your single requested byte somewhere in either one of these pages or just beyond the program break.
As long as you don't write beyond the allocated page, the virtual memory system is unaware of your transgression and won't segfault you. Of course, there's no way of knowing if or when an illegal access will happen, and thus in the C standard this behavior is undefined.
This question already has answers here:
Undefined, unspecified and implementation-defined behavior
(9 answers)
Is it undefined behaviour to access an array beyond its end, if that area is allocated? [duplicate]
(3 answers)
Array index out of bound behavior
(10 answers)
Getting no segmentation fault when exceeding the size that was allocated for a char * [duplicate]
(1 answer)
Closed 5 years ago.
The title may not be accurate. Please excuse me for being a completely new programmer in c. But it is a genuine question which I believe will benefit others who were as confused by memory and pointers as I was when learning my first low-level programming language, that is C.
Here is what I know in regard to this:
Pointers are variables that store memory addresses.
You can allocate a place in memory using the malloc function from the stdlib.h header file, which returns a pointer to the memory allocated.
The malloc function takes the size of what you want to store in bytes as a parameter
Which leads me to ask: What if you store something of a bigger size in the place in memory allocated by the malloc function, where you passed a smaller size as the parameter for the malloc function?
Naturally, the first thing I did was obviously try it. I take input using scanf, which then stores the input in the allocated memory. Here is the code:
#include <stdio.h>
#include <stdlib.h>
int main(){
char *string_pointer;
string_pointer = malloc(sizeof(char)*24);
if (string_pointer == NULL){
puts("Memory allocation failed:(");
return 1;
}else{}
scanf("%s",string_pointer);
printf("%s",string_pointer);
return 0;
}
You can see that I allocated a place in memory, passing in sizeof(char)*24 as the parameter. Then I stored the pointer of this memory in the string_pointer variable.
Now if I feed scanf with a string that is more than 24 characters (bigger size than the allocated memory), it still works, When I print out the contents of the memory, I get the whole string as it is, even though that means that it stored a string of a bigger size than what it can hold. This shows that I have an obvious misconception of how memory allocation works. It might be because that malloc doesn't allocate a memory that can only hold the size that I passed to malloc, and the whole size parameter thing is for a totally different purpose.
I am completely confused? How come I just stored a string in a memory allocated that can hold less than the size of the string?
This question already has answers here:
I can use more memory than how much I've allocated with malloc(), why?
(17 answers)
Closed 6 years ago.
C noob here. What does it matter what argument I give malloc when I can pass whatever size string to it later?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
char *str;
str = malloc(1*sizeof(char));
strcpy(str, "abcd");
printf(str);
printf("\n");
return 0;
}
This works fine. I would have thought I wouldn't be able to store more than 1 char in str from my understanding of what malloc is supposed to be.
malloc can end up actually allocating more than expected to maintain alignment/simplify the allocator.
What you're doing is undefined behavior, and among other things, "undefined" can mean "works, sometimes". Don't do this though, because the other options are not nearly so good. Some of the time, it will crash. Some of the time, it will appear to work, but it turns out you corrupted the heap, and at some later point, using or freeing some completely different allocation, you'll get "inexplicable" data or heap corruption related errors that aren't tied to the overflow in any obvious way.
It's a terrible idea, never rely on having even one byte more than you requested.
This question already has answers here:
Segmentation Fault - declare and init array in C
(3 answers)
Closed 8 years ago.
I have a query about using the memcpy() function.I have written the below program, it compiles but doesn't print an output. The .exe opens and the crashes. I am using Code Blocks as my IDE using GNU GCC compiler.
int main()
{
char a[]= "This is my test";
char *b;
memcpy(b,a,strlen(a)+1);
printf("After copy =%s\n",b);
return(0);
}
However, if I change the array *b to b[50] it works!! I don't understand why.
Please provide your suggestions!
Thanks!
Your pointer b is uninitialized. It is pointing to some random location in memory. So when you copy stuff into the memory which b is pointing to, bad things are likely to happen.
You need to initialize it; perhaps allocate some memory for it with malloc().
char *b = malloc(strlen(a) + 1);
And then free it when you're finished.
free(b);
You are lucky it did not crash when you used pointer - it should have.
When you copy memory, destination must be allocated first. If you use char b[50], you allocate 50 bytes for b on stack. If you use char *b, you did not allocate anything yet, and typically should do this using something like malloc : b = malloc(50);.
With malloc it will work, but then you should not forget to release that memory with free(b);.
If memory was allocated on stack, release happens automatically.