malloc을 통해서 동적 메모리 할당을 할때,

char *a = (char*)malloc(17);

a를 위와 같이 17만큼만 할당 후,

fread(a, 1, 20, fp); 와 같이 할당 받은 사이즈 보다 많은 값을 읽고난 후

char *b = (char*)malloc(17); 했을때 예외가 발생함...

따라서 동적 메모리 할당시 사용하는 메모리를 잘 계산해서 사용할 것.

문제 발생 소스는 너무 커서 생략.

Posted by 창신다이

//No.1

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

typedef struct _QPACKET {
int     nSize;
char  data[0];  //<--- 이 부분 data가 길어지더라도 시작 번지를 갖고 있는다
} QPACKET;


void aaa(int nSize, char *data)
{
QPACKET *test;
int a = 0;

a = sizeof(int);

test = (QPACKET*) malloc(sizeof(int) + strlen(data) + 1); //<--- 데이터의 길이 만큼 동적 메모리 할당

test->nSize = nSize;
strcpy(test->data, data);
printf("R: %s\n", test->data);

free(test);
}

void main(){
char data[12];
strcpy(data, "abcde");
aaa(strlen(data), data);
}


//No.2

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

typedef struct _QPACKET {
int     nSize;
char  *data;  <---  이 부분
} QPACKET;

void aaa(int nSize, char *data)
{
QPACKET *test;
int a = 0;

a = sizeof(int);

test = (QPACKET*) malloc(sizeof(QPACKET));
test->data = (char *) malloc(strlen(data)+1);  <--- malloc 한 번더

if(test->data==NULL){
 printf("메모리 할당 실패\n");
}

test->nSize = nSize;
strcpy(test->data, data);
printf("R: %s\n", test->data);

free(test->data);
free(test);
}

void main(){
char data[12];
strcpy(data, "abcde");
aaa(strlen(data), data);
}

Posted by 창신다이

BLOG main image
오랫동안 꿈을 그리는 사람은 마침내 그 꿈을 닮아 간다. -앙드레 말로- by 창신다이

공지사항

카테고리

분류 전체보기 (248)
공장이야기 (115)
Education (30)
회사이야기 (19)
일상 (73)

최근에 올라온 글

최근에 달린 댓글

최근에 받은 트랙백

Total :
Today : Yesterday :