SIGSEV on strcmp of memset string

后端 未结 3 563
自闭症患者
自闭症患者 2021-01-29 12:29

In the following program, i am expecting the for loop to stop after 3 elements. But it keeps on going indefinitely and fails later on with a coredump.

  1. is mal
3条回答
  •  死守一世寂寞
    2021-01-29 13:07

    Summarizing everything stated in comments and other answers, there are at least three (or, if you want to be pedantic, four) problems here:

    1. You need memset(str, 0, 10*sizeof(char *) (but see #4 below).
    2. You need to check for null pointers before calling strcmp, using a condition like str[i] != NULL && strcmp("",str[i])!=0 in your for loop.
    3. If you ever store 10 nonempty strings in the array, the loop's going to sail off the end, never finding an empty string.
    4. (pedantic) memset is not a good way to initialize an array of null pointers. (Strictly speaking it's not guaranteed to work at all.) As suggested by @user3121023 in a comment, a better way is char *str[10] = { NULL }.

    Instead of using an empty string (or a null pointer) as a marker for the end of your array of strings, you might consider keeping an explicit count in a separate variable. That's probably the more common approach.


    Addendum. You were asking whether you needed to allocate the strings. Memory does need to be allocated for the strings, but you do not necessarily need to dynamically allocate it by calling malloc. There are at least three ways to achieve the necessary allocation, and in two of them, the compiler does it for you. Here's an example of all three:

    char sample1[] = "Sample 1";
    
    char *sample2 = malloc(strlen("Sample 2") + 1);
    strcpy(sample2, "Sample 2");
    
    str[0] = "Sample 0";
    str[1] = sample1;
    str[2] = sample2;
    

提交回复
热议问题