-1

I wanted to code some simple DNA sequence comparison C source code

Here is my part of code

int main(){
    char* seq1 = (char*)malloc(sizeof(char)*10);
    char* seq2 = (char*)malloc(sizeof(char)*10);
    seq1 = "AAAAATTTTT";
    seq2 = "AAAATTTTGG";
    /* Compare these two sequences */
    free(seq1);
    free(seq2);
}

This code gave me error. ( something like heap error ... )

I removed the memory allocation lines and free memory part and then it gave me result without warnings and error.

whats the difference between I allocate memory first , set value and then free the memory and just not to do so?

Bartek Banachewicz
  • 38,596
  • 7
  • 91
  • 135
  • 1
    "( something like heap error ... )" isn't precise enough. Copy the *exact* error message you received. – Bartek Banachewicz Sep 25 '14 at 08:16
  • possible duplicate of [How to correctly assign a new String value in C](http://stackoverflow.com/questions/3131319/how-to-correctly-assign-a-new-string-value-in-c) – dandan78 Sep 25 '14 at 08:18

4 Answers4

4

Reason for error is that you are assigning string literals to the pointer after allocating space for them. Pointer to allocated space is lost with this assignment and that can't be freed and results in memory leak.

Further you are passing pointers to free which are no more returned by malloc family functions. This will invoke undefined behaviour.

haccks
  • 104,019
  • 25
  • 176
  • 264
3

seq1 is a pointer to a C-string. After you malloc'd some memory for your string, seq1 points to it. When you asssign a string literal to seq1, the pointer is overwritten and points to some static buffer.

You should rather use strcpy to "fill" the buffer allocated with malloc with data:

strcpy(seq1, "AAAAATTTTT");

But, this won't work because when mallocing, you didn't accomodate for the trailing 0. You should allocate strlen("AAAAATTTTT")+1 bytes for that string.

Tomo
  • 3,431
  • 5
  • 25
  • 28
2

"AAAAATTTTT" isn't char*; it's const char*. It has its own space and you're not supposed to free it.

The memory allocation you made worked (most probably) ok; however once you've overwritten it with your literals you've leaked that memory, and then tried to free the memory of the literals (which is most probably UB).

Bartek Banachewicz
  • 38,596
  • 7
  • 91
  • 135
1

You need to allocate enough space for 10 characters and a terminating '\0'
Use strcpy to assign the string to the pointer
The return from malloc does not need a cast

int main(){
    char* seq1 = malloc(sizeof(char)*11); // allows for 10 characters and terminating '\0'
    char* seq2 = malloc(sizeof(char)*11);
    strcpy ( seq1, "AAAAATTTTT"); // assign string to pointer
    strcpy ( seq2, "AAAATTTTGG");
    /* Compare these two sequences */
    free(seq1);
    free(seq2);
}
user3121023
  • 8,181
  • 5
  • 18
  • 16