1

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;



}
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
Jimmy Xu
  • 335
  • 1
  • 3
  • 7

3 Answers3

2

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.

Community
  • 1
  • 1
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
  • 1
    Just to add to this, even with this, the type of allocation in the OP's code `inputStrings=realloc(*inputStrings,i*sizeof(argv[i]));` doesn't make sense so that also needs to be fixed – Gopi Nov 29 '14 at 10:09
  • @Gopi Right. Updating. – Sourav Ghosh Nov 29 '14 at 10:10
2

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.

Artjom B.
  • 61,146
  • 24
  • 125
  • 222
Esakki Thangam
  • 355
  • 2
  • 7
0

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;
}
BLUEPIXY
  • 39,699
  • 7
  • 33
  • 70
  • `realloc` is not required for each elements because the required size is seen by `argc` in advance. – BLUEPIXY Nov 29 '14 at 11:20