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

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;
}

Related

Why is the structure causing a memory error?

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
struct bank
{
char *name [3];
char *ha[3];
int bal[3];
};
typedef struct bank bank;
int main()
{
bank *SBI;
SBI=(bank*) malloc(sizeof(bank));
strcpy(SBI->ha[0], "1234");
printf("SUCCESS");
return 0;
}
Why is the above code generating a memory write error? When I run the code it generates some error relating to memory. I am beginner in C programming. Can anyone help me about what is wrong in the code that is causing the error.
You also need to allocate space for your three strings ha[0], ha[1], ha[2]. Your malloc allocates memory for the bank structure, including three pointers, but these pointers need to be allocated too, with malloc or strdup for example:
for (int i = 0; i < 3; i++) {
bank->ha[i] = malloc(MY_STRING_MAXLENGTH);
}
which you later free:
for (int i = 0; i < 3; i++) {
free(bank->ha[i]);
}
free(SBI);
You are copying your string into unallocated memory.
strcpy(SBI->ha[0], "1234")
Use strdup instead of strcpy. Strdup will allocate the memory for you.

Realloc 2D and functions

I want to realloc a 2D matrix in a different function from main but unfortunately, I get an invalid pointer error. I have read other answers but I can't see where is my error. My code is:
void example(double* w, size_t s){
w=realloc(w,(s+1)*sizeof(double));
w[s]=3;
}
int main(int argc, char *argv[]){
double w[100][1];
int i;
for(i=0;i<100;i++){
example(w[i],sizeof(w[i])/sizeof(w[i][0])
}
free(w);
return 1;
}
so the first level of the array is always fixed but the second can change. What is wrong with this?
CORRECTION:
int main(int argc, char *argv[]){
double **w;
int i;
w=malloc(100*sizeof(double *));
for(i=0;i<100;i++){
w[i]=malloc(1*sizeof(double));
example(w[i],sizeof(w[i])/sizeof(w[i][0])
}
free(w);
return 1;
}
The w pointer is not dynamically allocated (it didn't come from realloc or malloc) so it is invalid to pass it as the argument to realloc. Also, you will need to pass the new pointer back to main if you want to free it in main.
You need to allocate memory before you can realloc or free memory. Also for every iteration you allocate memory you need to free it, you may free(w) but all it is doing is removing the memory reference to to w not actually freeing all the memory. For everything you malloc or realloc you need to go back through and free it so you don't have any memory leaks. You need would need a function like your example but to free all the memory instead of allocating it.
Just my thoughts

How to compose characters into a single string in memory?

I am working on a school assignment and I need a little bit of help.
My question is, how can I compose characters that are read in from a file into a single string of memory. Here is what i have so far.
My Code:
#include <stdio.h>
#include <stdlib.h>
char myString;
int main(int argc, char *argv[]){
FILE* fin;
char ch;
fin=fopen(argv[1],"r");
while((ch=fgetc(fin))!=EOF){
printf("%c\n", ch);
}
fclose(fin);
return 0;
}
My teacher said the last part of main is to be:
putchar(ā€˜\nā€™);
printf( myString );
return 0;
}
But I'm not sure how to put that within my code. Thank you ahead of time, Im also not looking to be just given the answer if you could help me work it out that would be great thank you again.
Updated code:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]){
FILE* fin;
int i;
char myString[3];
fin=fopen(argv[1],"r");
while(fgets(myString,sizeof(myString), fin)){
putchar('\n');
printf("%c\n", myString[i]);
}
fclose(fin);
return 0;
}
Im unsure if this code is exactly correct. It prints out the items within the file and puts a space between them. and there is an array being used for the string.
Im also not looking to be just given the answer
Fine.
Define a char array (mystring) large enough to hold your string
Define a counter to keep track of the position in the array
At each step store ch into the array
Remember to 0-terminate it (store 0 as the last element).
Things to note:
You will need to learn about realloc and grow the storage as you go if your program is to read arbitrarily long input. Better leave that for later
It's generally unsafe to printf(dynamicstr). What if it contains a "%d" ? It's better to printf("%s", dynamicstr).
You get to learn about memcpy and malloc. They are your friends.
--Jason
You need to read the applicable part of your textbook that explains what a "string" is in C. Without you understanding that, there's almost no way to answer your question without simply doing it for you.
A C "string" is a contiguous chunk of memory containing chars and is NULL terminated. You'll need to allocate that then place the characters into it as you read them from the file. Note that you have to make sure you don't go beyond the memory you've allocated while doing so, this is called a "buffer overflow".
#include <stdio.h>
#include <stdlib.h>
char* myString;
int main(int argc, char *argv[]){
FILE* fin;
fpos_t fsize = 0;
char ch;
char *pch;
fin=fopen(argv[1],"r");
fseek(fin,0,SEEK_END);
fgetpos(fin, &fsize);
rewind(fin);
pch = myString = (char*)malloc((fsize+1)*sizeof(char));
while((ch=fgetc(fin))!=EOF){
*pch++ = (char)ch;
}
*pch = '\0';
fclose(fin);
printf("%s", myString);//printf(myString);// need escape %
free(myString);
return 0;
}

Segmentation fault sprintf [c]

I need to pass two args to a shell script, here is the code:
#include <stdio.h>
#include <stdlib.h>
void main()
{
char *script;
int lines = 1;
sprintf(script, "/...path.../line.sh %d %d", lines, lines);
system(script);
}
The script works well, ive tried. But I always get Segmentation fault. The question is: why?
Thanks
You are writing to the memory location pointed to by script which hasn't been allocated any memory.
Try something like:
#include <stdio.h>
#include <stdlib.h>
void main()
{
char script[100]; // Allocate as much as you need here for your string, not
int lines = 1; // necessarily 100
sprintf(script, "/...path.../line.sh %d %d", lines, lines);
system(script);
}
You need to allocate space for script
char *script = malloc(/* string size */);
To be able to use it.
You didn't allocate any memory for script.
char *script; creates a pointer, but it has to point to something you've allocated, in your case its value is undefined. Use malloc to allocate the memory, and free when you're done.
change this line:
char *script;
to this:
char script[255];
The sprintf tries to write the result string to script, which you haven't initialised.
You're not allocating any memory for the variable script. The sprintf function expects that its first param is a pointer to already-allocated memory, but your script is never initialized, which means that it's null or garbage.
You are formatting into "script" without allocating any memory to receive the formatted string.
Instead, allocate:
char script[1024];

segmentation fault in simple string manipulation

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.

Resources