segmentation fault in simple string manipulation - c

This program is giving segmentation fault on execution. How do I fix that?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[])
{
int bufsize = 1024;
char *buf;
char *msg="GET /dumprequest HTTP/1.1";
memset (buf,0, bufsize);
strcpy(buf,msg);
puts(buf);
return 0;
}

You have no memory allocated for buf. Try:
const int bufsize = 1024;
char buf[bufsize];

The calls to memset() and strcpy() are trying to write to a pointer that is pointing to a random location rather than a malloc()ed block of memory, and that will certainly cause a problem.

You need to allocate some memory for buf.
Such as
buf = (char *) malloc (bufsize);
And when you're finished:
free (buf);
Or make it a char array.

Using gcc on Ubuntu 10.10 the above code works.
malloc() and free() could be used to allocate some memory.
free() being called at the end of the function.
buf = (char *) malloc (bufsize);
This will allocate memory of the size 1024 for the buf.

Related

Is there a way to write a program which keeps using more and more memory? I want to write a simple C program for that

I used the following code but the VIRT column in top command shows constant memory allocated.
#include <stdio.h>
int main (int argc, char *argv[])
{
while(1)
{
int *pointer;
pointer = malloc(10 * sizeof(int));
*(pointer+3) = 99;
}
}
You need to Initialize the memory.
Use memset to initialize the memory:
memset(pointer, 0, the_size);
Also you could use calloc that not only allocates memory but also fills it with zeros for you:
pointer = calloc(10, sizeof(int));
about calloc:
The C library function void *calloc(size_t nitems, size_t size) allocates the requested memory and returns a pointer to it. The difference in malloc and calloc is that malloc does not set the memory to zero where as calloc sets allocated memory to zero.

Why am I getting a segmentation fault when using realloc()?

This small testing program is reading strings from the command line, and I'm getting a seg fault. Can anyone help me?
I also want to ask about how is realloc() different from malloc()? I mean I think realloc() is way smarter so why do we even need malloc()? And for malloc() I know we have to copy the strings and malloc() into the new memory, but can anyone gives me an example of that?
#include <stdio.h>
#include <stdlib.h>
//reading the string from the command line
int
main(int argc, char *argv[]){
char** inputStrings;
int i;
for(i=1;i<argc;i++){
inputStrings=realloc(*inputStrings,i*sizeof(argv[i]));
inputStrings[i-1]=argv[i];
}
for(i=0;i<argc-1;i++){
printf("what is in the address: %s\n",inputStrings[i]);
}
free(inputStrings);
return 0;
}
you forgot to allocate memory to char** inputStrings;
To solve,
allocate memory to inputStrings and inputStrings[i]. [malloc()/ calloc()]
or,
allocate memory to inputStrings and set inputStrings[i] to NULL before realloc().
Check the man page of realloc().
Note: Please learn to use a debugger, like gdb. It's really helpful to pinpoint errors like the above ones.
Edit:
inputStrings=realloc(*inputStrings,i*sizeof(argv[i]));
is also wrong concept. You have to allocate memory to inputStrings and inputStrings[i] seperately. Check this answer for some help regarding this.
you should allocate the memory for that char** inputString. using the malloc or calloc first.
inputstring = malloc(sizeof(char*));
Then you should allocate the memory for each position with in the looping
inputString[i] = malloc(sizeof(char));
after that only you are able to reallocate the memory using realloc.
fixed example
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]){
char **inputStrings = NULL;
int i;
for(i=1; i<argc; i++){
inputStrings=realloc(inputStrings, i*sizeof(argv[i]));//check omitted
inputStrings[i-1]=argv[i];
}
for(i=0;i<argc-1;i++){
printf("what is in the address: %s\n", inputStrings[i]);
}
free(inputStrings);
return 0;
}

Why this program is crashing did i wrongly allocated memory

This program is crashing. Please tell me what's wrong with it. When I use an array instead of a pointer like Name[12] in the structure it doesn't crash. I guess there is some problem in dynamic memory allocation. Help please.
#include <stdio.h>
struct struct_tag
{
int number;
char *Name;
} struct_name;
main()
{
struct_name.number = 34;
char *Name = (char *) malloc(sizeof(char));
strcpy(struct_name.Name,"A");
printf("%d", struct_name.number);
}
You're allocating a single character:
char *Name = (char *) malloc(sizeof(char));
And then never using that memory for anything. You meant to allocate memory for struct_name.Name, undoubtedly. But even if you had done so, you're then filling it with two characters ('a' and '\0'):
strcpy(struct_name.Name,"A");
which will cause an entirely different bug.
You want to say:
struct_name.Name = malloc( 2 );
Since (a) you shouldn't cast the result of malloc() and (b) sizeof(char) is always 1 and (c) you need room for the 0 at the end of your string.
For errors:
You are allocating memeory for *Name however you are not allocating
memory for struct_name.Name. So first thing is you need to allocate memory for struct_name.Name
As you already know that you'll be storing "A" in
struct_name.Name you should allocate memory for 2 char.("A" is string i.e 'A' and '\0')
For warnings:
If you want to use strcpy function include string.h in your code.
Also if you are using malloc include stdlib.h in your code.
Try this fixed code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct struct_tag
{
int number;
char *Name;
}struct_name;
int main()
{
struct_name.number = 34;
struct_name.Name = malloc(sizeof(char)*2); // As you will store "A"
strcpy(struct_name.Name,"A");
printf("%d \t", struct_name.number);
printf("%s \n", struct_name.Name);
return 0;
}
first look code carefully.
char *Name = (char *) malloc(sizeof(char));
strcpy(struct_name.Name,"A");
Hare for what you allocated memory (char *Name) and in which you copied string(struct_name.Name)?
here you not allocate memory for struct_name.Name. Also you have allocate memory for one character and you tried to copy two characters.('A' and '\0').
It should be
struct_name.Name = malloc(2);

How to free memory that is allocated in a function but address is returned by that function?

I want to know how to free the memory I've dynamically allocated. I know that the memory will get automatically freed after program termination, but what if this function was used as part of a daemon. I believe I would have a memory leak, no?
Here is the code. It is a simple string reverse function.
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <assert.h>
char *my_string_rev(char *string)
{
// allocate memory to return the new string
char *out = malloc (sizeof (char));
assert(out);
// do things here
// ..
// ..
return out;
}
int main()
{
char *str = my_string_rev("true");
free(str);
return 0;
}
I've tried calling free(str) in main to find out that it won't work. Should I worry about freeing the memory returned by my_string_rev?
The above calling of my_string_rev does in fact work. When the string is longer than 4 characters. So when I call the function with "stackoverflow.com a b", I get this error:
Error in `./main': free(): invalid next size (fast): 0x088d2008 *
Is that because of malloc allocation? Should I be passing the length of the string to malloc?
char *out = malloc(strlen(string) + 1);
+ 1 because strlen does not count '\0' character.

simple string runtime error in C?

This code compiles fine but give segmentation fault error while running? Can anyone tell why?
#include <stdio.h>
#include <string.h>
#include <math.h>
int main() {
const char s2[] = "asdfasdf";
char* s1;
strcpy(s1, s2);
printf("%s", s1);
return 0;
}
You allocated space for a single pointer, s1, but not the bytes pointed at by s1.
A solution is to dynamically allocate memory for s1:
s1 = (char *)malloc(strlen(s2) + 1);
strcpy(s1, s2);
Keep in mind that you need to allocate one more byte of memory (the +1 in the call to malloc) than the number of characters in s2 because there is an implicit NULL byte at the end.
See C Memory Management (Stack Overflow) for more information.
You didn't allocate memory for s1. You have a pointer to s1 but no memory allocated for the strcpy to copy the value of s2 into.
char *s1 = malloc( strlen(s2) + 1 );
strcpy( s1, s2 );
You have not allocated any memory to s1. It is a pointer to nothing.
char* s1 = malloc(sizeof(s2));
strcpy(s1, s2);
printf("%s", s1);
free(s1);
The problem is that s1 does not have any memory associated with it. strcpy does not call malloc().
You could either do:
char s1[10];
or
char *s1 = malloc(10);
What they all said, you need to allocate the space for s1. What everyone else has posted will work just fine, however, if you want a simpler way to allocate space for an existing string and copy it into a new pointer then use strdup like this:
#include <stdio.h>
#include <string.h>
#include <math.h>
using namespace std;
int main() {
const char s2[] = "asdfasdf";
char* s1;
s1 = strdup(s2);
printf("%s", s1);
return 0;
}
Someone mentioned strdup earlier, that would be a way to use it. Most systems should support it since it is in the standard C libaries. But apparently some don't. So if it returns an error either write your own using the method already mentioned, or just use the method already mentioned ;)
No one yet has pointed out the potential of strdup (String Duplicate) to address this problem.
#include <stdio.h>
#include <string.h>
#include <math.h>
using namespace std;
int main() {
const char s2[] = "asdfasdf";
char* s1;
s1 = strdup(s2); // Allocates memory, must be freed later.
printf("%s", s1);
free(s1); // Allocated in strdup, 2 lines above
return 0;
}
You need to allocate the destination (and using namespace std; isn't C but C++, the rest of the code is C).
You have to allocate memory to the pointer s1. If you don't do that, it will be pointing somewhere unknown, and thus arriving at the segmentation fault. The correct code should be:
#include <stdio.h>
#include <string.h>
#include <math.h>
int main() {
const char s2[] = "asdfasdf";
char* s1 = malloc(21 * sizeof(s2[0]));
strcpy(s1,s2);
printf("%s",s1);
return 0;
}

Resources