1

The following is my code

int main(){
   char *movies[500];
   int i=0;

   while(*(movies[i])!='$'){
        scanf("%s",(movies[i]));
        i++;  
   }
}

The output is a segmentation fault. Can someone please explain?

1
  • Your while loop is testing movies[i] before it reads anything into it. It should probably be a do-while loop so it tests after reading. Commented Jan 19, 2015 at 13:36

2 Answers 2

3
movies[i] = malloc(<size>); 

Allocate memory to each pointer before writing something to it.

Your pointers movies[i] doesn't point to any valid memory location and you try to write to it which will lead to undefined behavior hence the crash.

Once done using the memory free() it accordingly

Sign up to request clarification or add additional context in comments.

6 Comments

why cant i use a do while loop as in something like and doesn't char *movies[500] automatically allocate space char *movies[500]; int i=0; do{ scanf("%s",(movies[i])); }while(*(movies[i++])!='$');
@AdityaSharma Yes the point is you need to allocate memory to your pointers what you have char *movies[500] is array of pointers and for each pointer you need to allocate memory
Then what is the use of it.I could directly use char movies[500][500];
@AdityaSharma There are 2 segments stack and heap. Dynamically you can allocate memory on heap using array of pointers and as and when needed . If you allocate memory on stack by creating an 2D array then there might be memory allocated but not used
when i do movies=(int )malloc(<size>);.It gives a warning: assignment from incompatible pointer type [enabled by default] movies[i] =(int) malloc(100); .why so??
|
0

First, you don't have an array of arrays; you have an array of pointers. When you do that, you must allocate the individual strings as you go. If you had an array of arrays, you would be declaring it like this:

char movies[500][500]; // <<== Not recommended

However, your approach is more economical in terms of memory.

Second, your exit condition (user enters $ for the first character of the movie name) will never be true, because you always check the value before movies[i] has been populated.

Here is how you can fix this:

char buf[500];
int count = 0;
for (;;) {
    scanf("%s", buf);
    // Check exit condition here
    if (buf[0] == '$') {
        break;
    }
    // Make a copy
    movies[count] = malloc(strlen(buf)+1);
    strcpy(movies[count++], buf);
}
...
// Don't forget to free the strings that you allocated
for (int i = 0 ; i != count ; i++) {
    free(movies[i]);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.