Jimmy Xu
Jimmy Xu

Reputation: 335

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;



}

Upvotes: 1

Views: 1902

Answers (3)

BLUEPIXY
BLUEPIXY

Reputation: 40155

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

Upvotes: 0

Esakki Thangam
Esakki Thangam

Reputation: 355

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.

Upvotes: 2

Sourav Ghosh
Sourav Ghosh

Reputation: 134396

you forgot to allocate memory to char** inputStrings;

To solve,

  1. allocate memory to inputStrings and inputStrings[i]. [malloc()/ calloc()]

or,

  1. 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.

Upvotes: 2

Related Questions