0

I need to use the algorithm of linked list in my program. I will explain quickly what it need to do:

My program generate a string with maximum size 2.000. I need to create a linked list of elements of the following type:

typedef struct List * News;


 struct List { 
 char * Text; 
 News next;
} ;

Since the maximum size of the struct is 2.000, to put the information of one struct it my text field, I want to use the exact size of the struct. So, I made the following function to create and add an element on the top of my linked list:

void InsertLL (News p, char M[]){

 char * text = (char *)malloc(strlen(M) * sizeof(char));
 strcpy(text, M);
 News s,t;
 t = malloc(sizeof(struct List));
 t-> Text = text;
 s=p;
 p=t;
 t -> next = s;

 }

The program run in a infinite loop, and after a while running, it crashes. Without the function InsertLL, it runs well (for example, if I don't care for the size of my struct and put it directly on my element). On debug mode, it doesn't crash, so I think it is some kind of memory problem that I couldn't solve yet.

is there something I am doing wrong when I call malloc?

Thanks for your help!

Giiovanna
  • 424
  • 6
  • 21

2 Answers2

3

You are not allocating enough space for text. You should consider space of null character as well so allocate strlen(M)+1 bytes.

sizeof(char) is always one byte and you need not to typecast the malloc result as void * is automatically and safely promoted to any other pointer type.

Change the code to char * text = malloc(strlen(M)+1);

Vallabh Patade
  • 4,960
  • 6
  • 31
  • 40
1

You are not allocating space for the null terminator. Pass strlen()+1 to malloc when allocating strings. Remember that strlen() returns the length of the string excluding the null terminating character.

Note that sizeof(char) is 1 by definition, and that you should not cast the return value of malloc. Your code should be

char * text = malloc(strlen(M) + 1);
Community
  • 1
  • 1
David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490