none
C access violation when using scanf_s() to fill a Set value RRS feed

  • Question

  • Hi there, I have an assignemt to implemet Union(), Intersect() and Devision() of sets of strings in C. As I understand it's going to be something like equivalent of HashSet<T> class in C#. At first I decided to make the body of the set - how I'm going to collect the string items and when I tried to fill some names in into the first set there is always this error. Is it caused by missuse of the pointers or it's something else?

    #include<stdlib.h>
    #include<stdio.h>
    #include<string.h>
    
    typedef struct
    {
    	char* value;
    }Set;
    
    void FillSet(Set *set, int elements)
    {
    	for (int i = 0; i < elements; i++)
    	{
    		scanf_s("%s", set[i].value);
    	}
    }
    void main()
    {
    	int length = 0;
    
    	printf("Type number of string elements in the set: ");
    	scanf_s("%d", &length);
    
    	Set *a = (Set*)malloc(length*sizeof(Set));
    
    	FillSet(a, length);
    
    	printf("The second element is: %s\n", a[1].value);
    
    	system("pause");
    	free(a);
    }

    Monday, March 10, 2014 8:22 PM

Answers

  • Read carefully the documentation on scanf_s(). If you are trying to read in a string, you need to allocate space for that string and also follow the address of that space with a parameter indicating the size of the space (in characters).

    You are allocating an array of Set's off the heap using a malloc() statement. I This means each element of array of Set's contains a member variable called value containing some junk data. That is, *value is undefined. Yet you pass that undefined junk value as the second parameter to scanf_s(). It should be of no surprise that this precipitates an error. On the other hand, if you defined Set as:

    struct
    {
       char value[100];
    }Set;

    and called scanf_s as:

    scanf_s("%s", set[i].value, 100);

    you might have better luck. I hope it is clear to you why.

    As a final thought, I suggest you should NOT allocate your array of Set's off the heap using malloc. Why not simply use a stack variable or a static global variable.

    • Marked as answer by Anna Cc Sunday, March 16, 2014 6:26 AM
    Monday, March 10, 2014 9:08 PM