I'm rather new to the C programming language and I'm very stuck. Whenever I try to assign a value to dynamically allocated string, I end up with a Segmentation Fault. Could someone help me by explaining why this happens. Following is a bit of my code that I think should provide enough information to help.

typedef char * Word;

typedef struct Panvowels
    {
        int num;
        Word firstFive[5];
        int firstFiveSize;
        Word shortest, longest;
    } PANVOWELS;

    PANVOWELS panvowel = {0, (Word)malloc(5 * WORDSIZE), 0,
                            (Word)malloc(WORDSIZE), (Word)malloc(WORDSIZE)};

    panvowel.shortest = "";
    panvowel.longest = "";

    panvowel.shortest[0] = 'a';

Recommended Answers

All 4 Replies

For starters I would initialize these like so

panvowel.shortest[0] = '\0';
panvowel.longest[0] = '\0';

Also you should never do batch memory allocations without checking to see if malloc failed..

Try initializing your structure like this.

PANVOWELS panvowel = {
			    0, 
			    {NULL, NULL, NULL, NULL, NULL}, 
			    0, 
			    NULL, 
			    NULL
			};

And then allocate your resources checking to make sure malloc succeeded.

I tried gerard4143's suggestion, but that ended in a segmentation fault within itself.
Also, I am using assert() to check the memory allocation, but felt it was unnecessary to include it here, seeing how it is not related to my problem.

Try running this code

#include <stdio.h>
#include <stdlib.h>

#define WORDSIZE 35

typedef struct Panvowels
    {
        int num;
        char* firstFive[5];
        int firstFiveSize;
        char* shortest;
	char* longest;
    } PANVOWELS;

int main()
{
    
  PANVOWELS panvowel = {
			    0, 
			    {NULL, NULL, NULL, NULL, NULL}, 
			    0, 
			    NULL, 
			    NULL
			};

  panvowel.shortest = (char*)malloc(WORDSIZE);
  
  if (!panvowel.shortest)
  {
    fputs("allocation failed!\n", stderr);
    exit(EXIT_FAILURE);
  }
  
  panvowel.shortest[0] = 'a';
  panvowel.shortest[1] = '\0';
  
  fprintf(stdout, "ans->%c\n", panvowel.shortest[0]);
  
  return 0;
}

A side note....When you have

typedef char* Word;

and then you have

Word something, something_else;

something is a character pointer while something_else is a character..


char *something, *something_else;

will create two character pointers....

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.