ererere ererere - 2 months ago 13
C Question

Invalid read of Size 1 when mallocing large String

I have a unique case where I'm trying to store a 4096 character string in a struct member. However, I'm mallocing the usually amount of memory for a shorter string, but am still getting a valgrind error:

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


struct List {
char * name;
int grade;
struct List * next;
};
int main(void) {
struct List * newList;
char * bigString;
int i;
bigString = malloc(sizeof(char)* 4096);

for (i=0; i<4096; i++)
bigString[i] = 'a';


newList = malloc(sizeof(struct List));
newList->next = NULL;
newList->name = malloc(strlen(bigString)+1);
free(bigString);


free(newList->name);
free(newList);


return 0;
}


the line:

newList->name = malloc(strlen(bigString)+1);


Returns an error
Invalid read of size 1


But wait a second, I'm mallocing the lenght of the string, plus 1 for the null terminator, what's going on here?

In fact I even tried this:

newList->name = malloc(sizeof(char) * strlen(bigString) +1);


And heck I even tried to null terminate the string after the malloc call:

newList->name[strlen(bigString)] = '\0';


To no avail..

I'm actually beyond confused as to what I've done wrong here. Any ideas?

Answer

bigString itself is not null-terminated, so strlen(bigString) results in trying to read past the end of the space allocated for bigString.