Why free() in C isn't work? [closed] - c

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
int main()
{
char* in = (char *)malloc(sizeof(char)*100);
in = "Sort of Input String with LITERALS AND NUMBERS\0";
free(in);
return 0;
}
Why this code isn't working with this error?
pointers(10144,0x7fff78a82000) malloc: *** error for object 0x10ba18f88: pointer being freed was not allocated
*** set a breakpoint in malloc_error_break to debug
bash: line 1: 10144 Abort trap: 6 '/Users/.../Documents/term2_sr/pointers'
[Finished in 0.1s with exit code 134]

Because in is re-assigned by in = "Sort of ...";.
Actually, you're doing free("Sort of ...");, which is obviously illegal.

in is a pointer. You set it with malloc(), you later change it to point to a literal. Then you try to free this poitner to a litteral (which was never allocated on the heap, so causes free() to fail) .
To copy a string, you have to use strcpy():
char* in = malloc(sizeof(char)*100);
strcpy (in, "Sort of Input String with LITERALS AND NUMBERS");
free(in);
Actually, in order to avoid accidental buffer overflows, you could also copy the string, taking into consideation its maximum length:
strncpy (in, "Sort of Input String with LITERALS AND NUMBERS", 100);

Related

Why strcat() causes causes segmentation fault in the fallowing code? [closed]

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 2 years ago.
Improve this question
Why the below code results in segmentation fault?
#include<studio.h>
#include<string.h>
int main ()
{
char *name="Kaveri";
char *rd="Rajshekhar";
strcat(name,rd);
puts(name);
return 0;
}
For strcat() to work, the destination buffer must be writable and long enough to hold the concatenated output with null termination. From the man page:
The strcat() function appends the src string to the dest string, overwriting the terminating null byte ('\0') at the end of dest, and then adds a terminating null byte. The strings may not overlap, and the dest string must have enough space for the result. If dest is not large enough, program behavior is unpredictable;
In your case, the destination is a pointer to the first element of a string literal, attempt to modify which invokes undefined behaviour.
Segmentation fault is one of the many side effects of undefined behaviour.
To solve this, either
make the name an array, with a big-enough dimension, like
char name[128] = "Kaveri";
use allocator function to allocate enough memory to name, like
char *name = malloc(128); //sizeof(char) == 1
strcpy(name, "Kaveri");
and then use name as the destination buffer for strcat.

can anyone explain the meaning of this peace of code from c [closed]

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 5 years ago.
Improve this question
the code is from C the code is written below:-
int main(){
char* time = (char *)malloc(10240 * sizeof(char));
scanf("%s",time);
return 0;
}
Error:
Because there is no prototype in scope for malloc the compiler interprets the result (of type void*) as type int.
Then it converts that value to type char* and assigns the resulting (meaningless) value to time.
Then, still using the meaningless value, it attempts to store there a value read and interpreted as an integer from standard input.
It then exits without doing anything more. Particularly it doesn't use the value read or release the memory (probably) allocated earlier.
it has first reserved memory dynamically from the heap by using malloc function, then it is scanning a string. pay attention to the format fo %s conversion specifier: the argument related to it is a pointer.(not for example time[0].)
don't forget that the memory should be free after the work is done
syntax: free (time);
char* time = (char *)malloc(10240 * sizeof(char));
Here, you use malloc() to allocate 10240 * sizeof(char) blocks of memory for you. sizeof(char) is equal to 4 bytes, so you are allocated 10240 * 4 = 40960 blocks of memory as int by default, as you have not specified any prototype in scope (seen as void*) for malloc()
You then cast the memory space to a char * and have *time point the first block in that memory allocated to you.
scanf("%s",time);
In this line, you try to store a value read as integer input from scanf() in time. Your format specifier is wrong here.
The program then terminates, without freeing the memory you allotted in it, and without doing anything with the inout you took with scanf().

Run-time error: *** glibc detected *** [closed]

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 6 years ago.
Improve this question
I was experimenting random things to know more about malloc, realloc and free and how they behave when they are used together.
I will include the code and my idea what I was trying to do.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(void)
{
char *str;
/* Initial memory allocation */
str = (char *) malloc(15);
strcpy(str, "63tczfqV4nqB2YnH9iFJbGvGyyDkvK341rrj0G0mo1PEYniOVHejVIFIQnJzHSSMRbuyGMCZ4M5HFMV4y1q4QgYqyxp2XkTjxaolKTkaw1r25S2Emz061tw1");
printf("String = %s, Address = %u\n", str, *str);
/* Reallocating memory */
str = (char *) realloc(str,16);
strcat(str, "12345678");
printf("String = %s, Address = %u\n", str, *str);
free(str);
return 0;
}
I expected my code to behave like this:
I created a character-type memory pointer to point (at max) 15 bytes of memory using malloc.
Using that character pointer, I saved 120 characters using strcpy.
I resized my character pointer to now point (at max) 16 bytes.
I concatenated, using strcat, 8 more characters to that memory buffer which is already holding 120 characters.
Now, my character pointer should point to 128 characters and I tried to reproduce that, however, it failed for 128 characters (but printed the earlier 120 characters which was saved using strcpy).
The exact error was this:
***** glibc detected *** ./a.out: realloc(): invalid next size: 0x0000000001690010 *****
and the console hung on this, i.e., it never moved past realloc line I suppose?
Let's look at the first two lines of your code:
str = (char *) malloc(15);
strcpy(str, "63tczfqV4nqB2YnH9iFJbGvGyyDkvK341rrj0G0mo1PEYniOVHejVIFIQnJzHSSMRbuyGMCZ4M5HFMV4y1q4QgYqyxp2XkTjxaolKTkaw1r25S2Emz061tw1");
At this point, you have broken the rules of the C language. strcpy will write past the end of str which causes undefined behavior.
Everything that happens after this point is kinda up in the air.

Where const char* value will store. what is stack crash & heap crash? [closed]

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
If I define char array like below
char arr[100] = "hello how are you";
where is this string("hello how are you") stored exactly? (stack/heap/data area/somewhere else?).
Stack Overflow vs stack crash
What is the difference between Stack Overflow and stack crash. When stack crash occurs?
Also heap overflow vs heap crash?
What happens when stack over flow/heap over flow occurs?
String literals are stored in read-only memory and persist for the length of the program. Thus it is safe to return this pointer from a function
.
const char *f()
{
return "Hello";
}
In your case, you copy the contents of the string literal into a local char array variable. So the storage of "hallo how are you" and char arr[100] are different.
You can modify arr and each time your program flow gets back to that line, arr will be initialized with the original string literal again. You can't return a pointer to arr from a function, because arr is only a local variable.
Tip: only char arr[] = "hallo how are you"; is necessary, unless you want to add more characters than are in your string literal.
I don't know what a "stack crash" is.
I'm not aware that heap can overflow. However, requests to allocate memory on the heap can fail. I don't know what a "heap crash" is.
When a stack overflow occurs, the program will typically crash. When a request to allocate heap memory fails, malloc will return NULL and new will throw std::bad_alloc

segmentation fault in after return? [closed]

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
I am getting Segmentation fault after return executes. Why is it coming after return and not in strcpy?
int main()
{
char a[2];
strcpy(a,"0123456789101112131415161718192021222324252627282930");
printf("%s\n",a);
return 0;
}
I am getting Segmentation fault after return executes. Why is it coming after return and not in strcpy?
You have made a common mistake called a buffer overflow. This results in undefined behavior, which is a standards answer. However, if you understand how a typical machine uses a stack, you can understand why it crashes when you return. Most CPUs use a down ward growing stack. So before you call strcpy, the stack is something like,
sp + 0 : a[0]
sp + 1 : a[1]
sp + 2 : padding
sp + 3 : padding
sp + 4: return address (four bytes)
The compiler machinery creates a call frame each time you use a function in 'C'. The return address exists as part of stack where the compiler allocates space for your a[] array. As it is under-sized for the string copy, you over-write the return address. This value isn't used until you return. The return address will be overwritten with something like the value 0x34353637 which is the binary pointer for the ASCII text '4567'.
It is advisable to use something like strncpy or an alternative. For example,
strncpy(a,"012345678...", sizeof(a));
a[sizeof(a)-1] = 0; /* ensure the string is terminated. */
Obviously you need to increase the size of your 'a' array if you want the full string to be printed.
Why is it coming after return and not in strcpy?
You get the segmentation fault when main returns because you overwrite critical data (saved frame pointer and return address) in the stack frame of main function and not in the stack frame of strcpy function.
As others already said, you invoke undefined behavior and anything can happen: from nothing to a nuclear war.
You're trying to load a string with a lot more than 2 characters into a char array that only holds 2 characters. This will cause a segmentation fault, since you are overwriting the memory allocated for the char array, which can also cause undefined behavior.
Your program overwrote the buffer, that would cause undefined behavior, which means literally anything could happen.

Resources